How to make HttpClient ignore Content-Length header

I use HttpClient to communicate with a server that I do not have access to. Sometimes the JSON response from the server is truncated.

The problem occurs when the Content-Length header is smaller than it should be (8192 vs 8329). This is similar to a server error that gives a smaller Content-Length header than the actual size of the response body. If I use Google Chrome instead of HttpClient, the answer will always be completed.

So I want the HttpClient to ignore the wrong Content-Length header and read until the end of the response. Can this be done? Any other solution is well appreciated. Thanks!

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 fully read the end of the JSON response without any truncation. However, I would like to use HttpClient as it is 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!!! 
+6
source share

All Articles