对于一个项目,我必须使用一个使用 GET 动词的 API,并且它必然需要“Content-type”属性,但这不是标准的,我想将此属性设置为“application/json” .
我正在使用 C# HttpClient,在查看了整个宇宙之后,我找不到一种方法来做到这一点。 我总是有一个“ProtocolViolationException”,显然......
有没有办法在 HttpClient 中使用“Content-type”和“GET”请求?
我正在使用此代码:
public async Task<HttpResponseMessage> GetAsync(string uri, double timeout = 0, string token = null)
{
using(var handler = new HttpClientHandler())
{
if(handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
using(var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
HttpResponseMessage httpResponseMessage = null;
if(timeout > 0)
{
client.Timeout = TimeSpan.FromSeconds(timeout);
}
if(!string.IsNullOrWhiteSpace(token))
{
request.Headers.Add("authorization", token);
}
request.Content = new StringContent("");
request.Content.Headers.Remove("Content-type");
request.Content.Headers.Add("Content-type", "application/json");
httpResponseMessage = await client.SendAsync(request);
return httpResponseMessage;
}
}
}
请勿在 GET 请求中设置 Content-Type。相反,假设您希望接收 JSON 结果,请设置 Accept 标头。