C# HttpClient ProtocolViolationException
本文关键字:ProtocolViolationException HttpClient | 更新日期: 2023-09-27 17:51:11
对于一个项目,我必须使用一个API,使用GET动词,这必然需要"Content-type"属性,但这不是标准的,我想把这个属性设置为"application/json"。
我正在使用c# HttpClient,在整个宇宙中寻找后,我找不到一种方法来做到这一点。我总是有一个"ProtocolViolationException",显然…
是否有办法使用"内容类型"answers"GET"请求与HttpClient ?
我使用这个代码
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标头。