HttpClient替換HttpWebRequest--以GET和POST請求爲例說明

首先說一下HttpRequest、WebClient和HttpClient的關係:HttpRequest是基層的請求方式,WebClient是對HttpRequest的簡化封裝,在WebClient中有對HttpRequest的默認設置;HttpClient是重寫的請求方式,相對於HttpRequest更簡單實現異步請求,是.NetCore中更推崇的方式。編程

說明:如下代碼中 在GetAccessToken(Async)中調用了調用了PostMail(Async)方式,其中在GetAccessToken(Async)實現GET請求,在PostMail(Async)中實現POST請求json

1、對比一下HttpRequest與HttpClient實現GET請求的過程區別(其實很類似,但HttpClient輕鬆實現了異步)api

1)HttpRequest的GET請求服務器

 public ActionResult<string> GetAccessToken()
        {  //GET獲取accessToken的參數 corid
            string uri = "你的URL";
            //建立請求
  //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            //WebClient是對HttpWebRequest的抽象,WebClient使用簡單,但速度慢;Restsharp兼具WebClient和HttpWebClient的優勢;HttpClient是.NetCore中的概念,更適合異步編程
            WebRequest request = WebRequest.Create(uri);
            //請求設置
            request.Credentials = CredentialCache.DefaultCredentials;
            //建立應答接收
            WebResponse response = request.GetResponse();
            //建立應答讀寫流
            string accessToken;
            using (Stream streamResponse=response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(streamResponse);
                string responseFromServer = reader.ReadToEnd();
                JObject res = (JObject)JsonConvert.DeserializeObject(responseFromServer);
                 accessToken = res["access_token"].ToString();
                reader.Close();
            }
            //得到許可證憑證
            PostMail(accessToken);
            //關閉響應
            response.Close();
            return "success";
        }

2)HttpClient的GET請求app

public async Task<ActionResult<string>> GetAccessTokenAsync()
        {
            string uri = "你的URL";
            HttpClientHandler handler = new HttpClientHandler
            {
                //設置是否發送憑證信息,有的服務器須要驗證身份,不是全部服務器須要
                UseDefaultCredentials = false
                
            };
            HttpClient httpClient = new HttpClient(handler);
            HttpResponseMessage response = await httpClient.GetAsync(uri);
            response.EnsureSuccessStatusCode();
            string accessToken;
            //回覆結果直接讀成字符串
            string resp = await response.Content.ReadAsStringAsync();
            JObject json = (JObject)JsonConvert.DeserializeObject(resp);
            accessToken = json["access_token"].ToString();
            //採用流讀數據
            //using (Stream streamResponse = await response.Content.ReadAsStreamAsync())
            //{
            //    StreamReader reader = new StreamReader(streamResponse);
            //    string responseFromServer = reader.ReadToEnd();
            //    JObject res = (JObject)JsonConvert.DeserializeObject(responseFromServer);
            //    accessToken = res["access_token"].ToString();
            //    reader.Close();
            //}
            //得到許可證憑證
            PostMailAsync(accessToken);
            //關閉響應
            return "success";
        }

2、對比一下HttpRequest與HttpClient實現POST請求的過程區別異步

1)HttpRequest的POST請求async

  public void PostMail(string accessToken)
        {    //POST的API
            string uri = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            //建立請求
            WebRequest myWebRequest = WebRequest.Create(uri);
            //請求設置
            myWebRequest.Credentials = CredentialCache.DefaultCredentials;
            myWebRequest.ContentType = "application/json;charset=UTF-8";
            myWebRequest.Method = "POST";
            //向服務器發送的內容
            using (Stream streamResponse = myWebRequest.GetRequestStream())
            {
                //建立JSON格式的發送內容
                JObject postedJObject = new JObject
                {
                    //在此處設置發送內容及對象
                    { "touser", "Heavy" },
                    { "msgtype", "text" },
                    { "agentid", 1000002 }
                };
                JObject text = new JObject
            {
                {"content","內容來自網站--內容可自行編輯--heavy"}
            };
                postedJObject.Add("text", text);
                postedJObject.Add("safe", 0);
                //將傳送內容編碼
                String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
                byte[] byteArray = Encoding.UTF8.GetBytes(paramString);
                //向請求中寫入內容
                streamResponse.Write(byteArray, 0, byteArray.Length);
            }
            //建立應答
            WebResponse myWebResponse = myWebRequest.GetResponse();
            //建立應答的讀寫流
            string responseFromServer;
            using (Stream streamResponse = myWebResponse.GetResponseStream())
            {
                StreamReader streamRead = new StreamReader(streamResponse);
                responseFromServer = streamRead.ReadToEnd();
            }
            //關閉應答
            myWebResponse.Close();
        }

2)HttpClient的POST請求異步編程

 public async void PostMailAsync(string accessToken)
        {
            string uri = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            HttpClientHandler handler = new HttpClientHandler
            {
                UseDefaultCredentials = true,
               
            };
            HttpClient httpClient = new HttpClient(handler);
            JObject postedJObject = new JObject
                {
                    //在此處設置發送內容及對象
                    { "touser", "Heavy" },
                    { "msgtype", "text" },
                    { "agentid", 1000002 }
                };
            JObject text = new JObject
            {
                {"content","內容來自網站--內容可自行編輯--heavy"}
            };
            postedJObject.Add("text", text);
            postedJObject.Add("safe", 0);
            //將傳送內容編碼
            String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
            //byte[] byteArray = Encoding.UTF8.GetBytes(paramString);
            HttpContent httpContent = new StringContent(paramString,Encoding.UTF8,"application/json");
            HttpResponseMessage response = await httpClient.PostAsync(uri, httpContent);           //用來判斷是否接收成功,不然拋出異常
            response.EnsureSuccessStatusCode();
        }
相關文章
相關標籤/搜索