• 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就几行代码搞定,舒服。。。

  • 相关阅读:
    Linux 命令行——Shell 环境变量的查看、配置、激活
    编程2016 1
    【论文阅读】An Evaluation of Concurrency Control with One Thousand Cores
    CarSim仿真快速入门(十七)—ADAS范围和跟踪传感器
    Vue webStorage 浏览器本地存储数据(附项目实战案例!)
    java实际项目反射、自定义注解的运用实现itext生成PDF的详细应用教程
    linux中在vscode中使用docker
    【算法篇】四种链表总结完毕,顺手刷了两道面试题紧张的羊
    OA系统源码
    学习Oracle数据库的新建表的基本操作(二)
  • 原文地址:https://blog.csdn.net/u012835032/article/details/125562557