对于一个项目,我要使用一个使用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;
}
}
}
提前致谢:)
答案 0 :(得分:0)
不要在GET请求中设置Content-Type。相反,假设您希望收到JSON结果,请设置Accept标头。