我正在使用HttpClient与我无法访问的服务器进行通信。有时,服务器的JSON响应会被截断。
当Content-Length标头小于它应该的值时,会出现问题(8192对8329)。这似乎是服务器上的一个错误,它提供了比响应主体的实际大小更小的Content-Length标头。如果我使用谷歌浏览器而不是HttpClient,则响应始终完成。
因此,我想让HttpClient忽略错误的Content-Length标头并读取到响应的结尾。有可能吗?任何其他解决方案都很受欢迎。谢谢!
这是我的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!
编辑1:
如果我使用HttpWebRequest,它可以完全读取到JSON响应的末尾而不会截断。但是,我想使用HttpClient,因为它有更好的async / await。
这是使用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!!!