zoukankan      html  css  js  c++  java
  • HttpClient请求设置Content-Type标头空格问题

    1.进行HttpClient请求时,对接一些第三方厂商的接口时,需要设置

    Content-Type:application/json;charset=utf-8

    但是在进行http接口访问时,会自动在Content-Type结束位置与charset开始位置加空格,导致无法使用HttpClient请求接口数据。

    Content-Type:application/json; charset=utf-8

    需要使用http方式重构

    content.Headers.ContentType = new MediaTypeHeaderValueClass("application/json");

    需要把这个MediaTypeHeaderValueClass继承MediaTypeHeaderValue方法重写tostring里面参数方法即可。

    // <summary>
    ///
    /// </summary>
    public class MediaTypeHeaderValueClass : MediaTypeHeaderValue
    {
    /// <summary>
    ///
    /// </summary>
    /// <param name="mediaType"></param>
    public MediaTypeHeaderValueClass(string mediaType) : base(mediaType)
    {
    }
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
    if (string.IsNullOrWhiteSpace(base.CharSet))
    {
    return base.MediaType + ";charset=utf-8";
    }
    return base.MediaType + ";charset=" + base.CharSet;
    }
    }
     
    调用方法
    HttpClient client = new HttpClient(new HttpClientHandler
    {
    MaxConnectionsPerServer = 100000,
    UseDefaultCredentials = false,
    AllowAutoRedirect = false,
    UseCookies = false,
    Proxy = null,
    UseProxy = false,
    AutomaticDecompression = DecompressionMethods.GZip
    });
    var content = new StringContent(strParam);
    content.Headers.ContentType = new MediaTypeHeaderValueClass("application/json");
    content.Headers.ContentType.CharSet = "utf-8";
    var msg = new HttpRequestMessage();
    msg.Content = content;
    msg.Method = HttpMethod.Post;
    msg.RequestUri = new Uri(Url);
    var rest = await client.SendAsync(msg);
  • 相关阅读:
    Beans
    Redis记录-Redis命令
    Redis记录-Redis介绍
    RESTful记录-RESTful服务
    RESTful记录-RESTful内容
    RESTful记录-RESTful介绍
    HTTP记录-HTTP介绍
    Solr记录-solr检索和查询数据
    Solr记录-solr文档xml
    Solr记录-solr内核与索引
  • 原文地址:https://www.cnblogs.com/wlming/p/14524509.html
Copyright © 2011-2022 走看看