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);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM