• 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

    代码如下,简单好用 

    1. public static async Task<string> PostUrlencodedAsync(string url, Dictionary<string, string> dic)
    2. {
    3. using (HttpClient _httpClient = new HttpClient())
    4. {
    5. HttpContent httpContent = new FormUrlEncodedContent(dic);
    6. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    7. var response = await _httpClient.PostAsync(url, httpContent);
    8. return await response.Content.ReadAsStringAsync();
    9. }
    10. }

     

    application/json

    application/json 对应的ContentType类型是StringContent,StringContent构造函数需要一个json字符串类型的参数,就是一个object或者List集合啥的转字符串就行。

    如果需要传参,像是带个token啥放在请求头里面。

    直接用键值对的方式传进来,然后循环加到请求头,方便快捷。

    1. public static async Task<string> PostJsonAsync(string url, string jsonData, Dictionary<string, string> dic)
    2. {
    3. using (HttpClient _httpClient = new HttpClient())
    4. {
    5. HttpContent httpContent = new StringContent(jsonData);
    6. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    7. if (dic.Count > 0)
    8. {
    9. foreach (var item in dic)
    10. {
    11. _httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
    12. }
    13. }
    14. var response = await _httpClient.PostAsync(url, httpContent);
    15. return await response.Content.ReadAsStringAsync();
    16. }
    17. }

    印象中以前要弄个http请求啥的,记得要写一堆代码,现在HttpClient就几行代码搞定,舒服。。。

  • 相关阅读:
    【FreeSwitch开发实践】UniMRCP编译与安装
    Redis的主从复制搭建
    PB系统函数介绍:共享对象函数
    HTTP请求交互基础(基于GPT3.5,持续更新)
    MYSQL逻辑架构与存储引擎
    OpenCV4之C++入门详解
    【药材识别】基于matlab GUI SVM色差色温判断药材炮制程度系统【含Matlab源码 2241期】
    vue后台开发第一步
    GO微服务实战第八节 如何基于 Go-kit 开发 Web 应用:从接口层到业务层再到数据层
    SQL日期字段去时分秒
  • 原文地址:https://blog.csdn.net/u012835032/article/details/125562557