How to make HttpClient ignore Content-Length header

时光总嘲笑我的痴心妄想 提交于 2020-06-24 22:47:45

问题


I am using HttpClient to communicate with a server which I don't have access to. Sometimes the JSON response from the server is truncated.

The problem occurs when the Content-Length header is smaller than what it should be (8192 vs. 8329). It seems like a bug on the server which gives a smaller Content-Length header than the actual size of the response body. If I use Google Chrome instead of HttpClient, the response is always complete.

Therefore, I want to make HttpClient to ignore the wrong Content-Length header and read to the end of the response. Is it possible to do that? Any other solution is well appreciated. Thank you!

This is the code of my 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:

If I use HttpWebRequest, it can read to the end of the JSON response completely without any truncation. However, I would like to use HttpClient since it has better async/await.

This is the code using 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!!!

来源:https://stackoverflow.com/questions/33477662/how-to-make-httpclient-ignore-content-length-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!