.net HttpClient的使用


   在程序用調用 Http 接口、請求 http 資源、編寫 http 爬蟲等的時候都需要在程序集中進行 Http 請 求。  很多人習慣的 WebClient、HttpWebRequest 在 TPL 下很多用起來不方便的地方,TPL 下推薦使 用 HttpClient(using System.Net.Http;)。 

   HttpClient 發出 Get 請求獲取文本響應: string html = await hc.GetStringAsync("http://www.rupeng.com"); 

  HttpClient發出Post請求使用Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content) 方法,第一個參數是請求的地址,第二個參數就是用來設置請求內容的。HttpContent 是 抽象類,主要的子類有 FormUrlEncodedContent(表單格式請求)、 StringContent(字符串 請求)、 MultipartFormDataContent(Multipart 表單請求,一般帶上傳文件信息)、 StreamContent(流內容)。使用提前寫好的“HttpClient 用測試服務器端”部署到 IIS,然 后方便測試。

 

注意以下例子都以例子a,中的方式一為基准。代碼都是放到async標記的方法里面

a)表單格式請求,報文體是“userName=admin&password=123”這樣的格式 

方式一: 
private async Task<stirng> test()
{
  HttpClient client = new HttpClient();
  Dictionary<string, string> keyValues = new Dictionary<string, string>();
  keyValues["userName"] = "admin"; 
  keyValues["password"] = "123"; 
  FormUrlEncodedContent content = new FormUrlEncodedContent(keyValues); 
  var respMsg = await client.PostAsync("請求的鏈接URL",content);// 不要錯誤的調用 了 PutAsync,應該是 PostAsync 
  string msgBody = await respMsg.Content.ReadAsStringAsync(); MessageBox.Show(respMsg.StatusCode.ToString()); MessageBox.Show(msgBody);
  return "ok";
}

方式二:
private Task<stirng> test()
{
  HttpClient client = new HttpClient();
   Dictionary<string, string> keyValues = new Dictionary<string, string>();
   keyValues["userName"] = "admin"; keyValues["password"] = "123";
   FormUrlEncodedContent content = new FormUrlEncodedContent(keyValues);
   var respMsg = client.PostAsync("http://127.0.0.1:6666/Home/Login/", content);
   // 不要錯誤的調用 了 PutAsync,應該是 PostAsync 
   HttpResponseMessage mess = respMsg.Result;
            
   Task<string> msgBody =  mess.Content.ReadAsStringAsync();
            
   MessageBox.Show("OK");
  //
msgBody.Result會阻止當前線程的繼續執行,等待要執行線程結束
  MessageBox.Show(msgBody.Result);   return "ok";
}

b)普通字符串做報文

string json = "{userName:'admin',password:'123'}";
HttpClient client = new HttpClient(); 
StringContent content = new StringContent(json);
//contentype 必不可少 content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var respMsg = await client.PostAsync("地址URL", content);
string msgBody = await respMsg.Content.ReadAsStringAsync();
MessageBox.Show(respMsg.StatusCode.ToString());
MessageBox.Show(msgBody);

c)上傳文件

HttpClient client = new HttpClient(); 
MultipartFormDataContent content = new MultipartFormDataContent(); 
content.Headers.Add("UserName","admin");
content.Headers.Add("Password", "123"); using (Stream stream = File.OpenRead(@"D:\temp\logo 透明.png"))
{ content.Add(
new StreamContent(stream), "file", "logo.png"); var respMsg = await client.PostAsync("上傳地址 URL", content); string msgBody = await respMsg.Content.ReadAsStringAsync();
  MessageBox.Show(respMsg.StatusCode.ToString());
  MessageBox.Show(msgBody); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM