[英]HTTP 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'
[英]API Get requires Content-Type application/json;charset=UTF-8 - Issue with Http Client
我正在使用需要将 Content-Type 设置为application/json;charset=UTF-8的 API 服务。
如果我在没有charset=UTF-8 的情况下发出请求,我会得到一个406 - Not Acceptable 。
我可以根据需要通过 Postman 设置 Content-Type 进行调用,但是如果我使用 my.Net Http Client,我会收到错误消息:
System.FormatException:“值‘application/json;charset=UTF-8’的格式无效。”
无论如何我可以解决此验证并强制 Http 客户端接受该值吗?
更新:
这是我最近的尝试,它仍然会抛出错误。
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=UTF-8");
更新:Content-Type 确实是一个无效的标头。 API 开发人员应我们的要求将其删除。
尝试设置属性:
new MediaTypeHeaderValue("application/json")
{
CharSet = Encoding.UTF8.WebName
};
试试这个
HttpClient httpClient= new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
不确定是否仍然相关,但我最近遇到了同样的问题,并且能够通过以下方式设置标头来解决:
string str = $"application/vnd.fmsstandard.com.Vehicles.v2.1+json; charset=UTF-8";
client.DefaultRequestHeaders.Add("Accept", str);
尝试在 UTF-8 周围添加双引号,如下所示:
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=\"UTF-8\"");
编辑:
好的,尝试这样的事情。 它在本地使用我已经拥有的 WebApi 为我工作。 请注意,有一个标头规范说明什么内容类型将被接受,然后有一个标头说明什么内容类型将随请求一起发送。 对于这个例子,它们都是 JSON:
public static async Task<string> HttpClient(string url)
{
using(HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json")); // ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
request.Content = new StringContent("{\"id\" : 1}",
Encoding.UTF8,
"application/json"); // REQUEST header
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
我只向其中添加了身份验证标头,它对我有用。 AuthToken
是字符串变量或令牌本身。 我省略了内容类型标头,它就可以正常工作。 下面是代码; Response
是一个必须序列化为Jobject
的字符串。
{
String Response = null;
HttpClient client = new HttpClient(CertByPass());
client.Timeout = TimeSpan.FromMinutes(5);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthToken);
Response = await client.GetStringAsync(url);
}
尝试创建一个客户端助手类,例如:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(whatever your url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return client;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.