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

  • 相关阅读:
    初识C++|类与对象(上)
    宝塔下 php7.4 使用kafka
    cnpm : 无法加载文件 C:\Users\XXX\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本——解决办法
    docker root dir 迁移方案
    Java字符串查找
    copilot 产生 python工具函数并生成单元测试
    SpringBoot复习:(60)文件上传的自动配置类MultipartAutoConfiguration
    腾讯云优惠券种类、领取方法及使用教程分享
    logsim&worldsim&场景库
    想过为什么家里的IP是192.168开头的吗?
  • 原文地址:https://blog.csdn.net/u012835032/article/details/125562557