.Net Core 版的 HttpClient 怎么设置 accept 值为 application/json; charset=utf-8。
首先Accept
与Accept-Charset
是分开的,两个属性。
其次application/json; charset=utf-8
是Content-Type
的写法。
C# 代码:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json", 1));
client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8", 1));
using var body = new StringContent("{A:1, B:2}", Encoding.UTF8, "application/json");
var resp = await client.PostAsync("/manager/api/login", body);
请求头:
......
Accept: application/json; q=1.0
Accept-Charset: utf-8; q=1.0
Content-Type: application/json; charset=utf-8
谢了,已经解决了。确实是分开了,找了好久。_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json") { CharSet = "utf-8" });
var stringContent = new StringContent(json, Encoding.UTF8);
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream") { CharSet = "utf-8" };
对接方的接口要求如图
即:Http Header 必须是这种格式,还要参与签名计算,你那种写法调不通。
Accept:application/json; charset=utf-8
Content-Type:application/octet-stream; charset=utf-8