[英]How to make HttpClient ignore Content-Length header
I am using HttpClient to communicate with a server which I don't have access to.我正在使用 HttpClient 与我无权访问的服务器进行通信。 Sometimes the JSON response from the server is truncated.有时来自服务器的 JSON 响应会被截断。
The problem occurs when the Content-Length header is smaller than what it should be (8192 vs. 8329).当 Content-Length 标头小于应有的值(8192 与 8329)时,就会出现问题。 It seems like a bug on the server which gives a smaller Content-Length header than the actual size of the response body.这似乎是服务器上的一个错误,它提供了比响应正文的实际大小更小的 Content-Length 标头。 If I use Google Chrome instead of HttpClient, the response is always complete.如果我使用 Google Chrome 而不是 HttpClient,响应总是完整的。
Therefore, I want to make HttpClient to ignore the wrong Content-Length header and read to the end of the response.因此,我想让 HttpClient 忽略错误的 Content-Length 标头并读取到响应的末尾。 Is it possible to do that?有可能这样做吗? Any other solution is well appreciated.任何其他解决方案都非常受欢迎。 Thank you!谢谢!
This is the code of my HttpClient:这是我的 HttpClient 的代码:
var client = new HttpClient();
client.BaseAddress = new Uri(c_serverBaseAddress);
HttpResponseMessage response = null;
try
{
response = await client.GetAsync(c_serverEventApiAddress + "?location=" + locationName);
}
catch (Exception e)
{
// Do something
}
var json = response.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<JObject>(json); // The EXCEPTION occurs HERE!!! Because the json is truncated!
EDIT 1:编辑 1:
If I use HttpWebRequest, it can read to the end of the JSON response completely without any truncation.如果我使用 HttpWebRequest,它可以完全读取到 JSON 响应的末尾而不会被截断。 However, I would like to use HttpClient since it has better async/await.但是,我想使用 HttpClient,因为它具有更好的 async/await。
This is the code using HttpWebRequest:这是使用 HttpWebRequest 的代码:
var url = c_serverBaseAddress + c_serverEventApiAddress + "?location=" + "Saskatchewan";
var request = (HttpWebRequest)WebRequest.Create(url);
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var response = (HttpWebResponse)request.GetResponse();
StringBuilder stringBuilder = new StringBuilder();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
stringBuilder.Append(line);
}
}
var json = stringBuilder.ToString(); // COMPLETE json response everytime!!!
You could try specifying the buffer size of the response content您可以尝试指定响应内容的缓冲区大小
var client = new HttpClient();
client.MaxResponseContentBufferSize = <your_buffer_size>;
Where the property MaxResponseContentBufferSize means:其中属性 MaxResponseContentBufferSize 意味着:
Gets or sets the maximum number of bytes to buffer when reading the response content.获取或设置读取响应内容时要缓冲的最大字节数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.