.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: emplogo 透明.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); }
原文地址:https://www.cnblogs.com/mykcode/p/7833090.html