HttpClient Post x-www-form-urlencoded Or 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就几行代码搞定,舒服。。。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑小晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值