HttpClient Post x-www-form-urlencoded Or json
HttpClient post application/x-www-form-urlencoded 或 application/json 格式数据
框架 .NET Core 3.1
HttpClient :Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
通俗点说
HttpClient是用来发http请求并获取结果内容的。
ContentType是用来指定请求内容的数据格式的,比如:application/x-www-form-urlencoded 和 application/json。
话不多说,下面看一下怎么用。
application/x-www-form-urlencoded
application/x-www-form-urlencoded 对应的ContentType类型是FormUrlEncodedContent,FormUrlEncodedContent 构造函数需要一个键值对类型的参数,放Dictionary<string, string>这样的就行。
数据格式就是URL传参那样:account=test&password=test123
代码如下,简单好用
public static async Task<string> PostUrlencodedAsync(string url, Dictionary<string, string> dic)
{
using (HttpClient _httpClient = new HttpClient())
{
HttpContent httpContent = new FormUrlEncodedContent(dic);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
application/json
application/json 对应的ContentType类型是StringContent,StringContent构造函数需要一个json字符串类型的参数,就是一个object或者List集合啥的转字符串就行。
如果需要传参,像是带个token啥放在请求头里面。
直接用键值对的方式传进来,然后循环加到请求头,方便快捷。
public static async Task<string> PostJsonAsync(string url, string jsonData, Dictionary<string, string> dic)
{
using (HttpClient _httpClient = new HttpClient())
{
HttpContent httpContent = new StringContent(jsonData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (dic.Count > 0)
{
foreach (var item in dic)
{
_httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
var response = await _httpClient.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
印象中以前要弄个http请求啥的,记得要写一堆代码,现在HttpClient就几行代码搞定,舒服。。。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)