httpclient GET 与POST方法

httpclient GET 与POST方法

在程序用调用 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 PostAsync(string requestUri, HttpContent content) 方法,
  第一个参数是请求的地址
  第二个参数就是用来设置请求内容的。HttpContent 是 抽象类,主要的子类有 FormUrlEncodedContent(表单格式请求)、 StringContent(字符串 请求)、 MultipartFormDataContent(Multipart 表单请求,一般带上传文件信息)、 StreamContent(流内容)。

注意以下例子都以例子a,中的方式一为基准。代码都是放到async标记的方法里面

  • a)表单格式请求,报文体是 “userName=admin&password=123” 这样的格式
  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(); 
}

b)普通字符串做报文

string json = "{userName:'admin',password:'123'}";
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();

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);
}   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值