System.Net.Http.HttpRequestException:将内容复制到流时出错。---> System.IO.IOException:响应过早结束



我使用以下代码来调用一些http api的

public static async Task<GenerricApiResponse> ProcessWebRequest<T>(string url, T req,ILog Logger, int timeoutInSeconds = 0)
{
var obj = new GenerricApiResponse();
try
{
using (var client = new HttpClient())
{
var jsonRequest = JsonSerializer.Serialize(req);
client.DefaultRequestHeaders.ExpectContinue = false;
var content = new StringContent(jsonRequest);
content.Headers.Clear();
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (timeoutInSeconds > 0)
{
client.Timeout = new TimeSpan(0, 0, timeoutInSeconds);
}
var response = await client.PostAsync(url, content);                    
obj.HttpResponseCode = response.StatusCode;
try
{
string responsecontent = null;
responsecontent = response.Content.ReadAsStringAsync().Result;
if (response.Content != null && response.Content.Headers != null)
{
obj.ResponseContentType = response.Content.Headers.ContentType.MediaType;
if (responsecontent != null && obj.ResponseContentType == "text/html")
{
if (responsecontent != null && responsecontent.Length > 1000)
{
responsecontent = responsecontent.Substring(0, 1000) + "...";
}
}
}
obj.Response = responsecontent;
}
catch
{
obj.IsError = true;
}
}
}
catch (Exception ex)
{               
if (ex.InnerException is TimeoutException)
{
ex = ex.InnerException;
}
obj.IsError = true;
obj.Exception = ex;
obj.Response = ex.Message;                
}
return obj;
}

但是得到错误

System.Net.Http.HttpRequestException:将内容复制到流时出错。 ---> System.IO.IOException:响应过早结束。

知道我的代码中缺少什么或我做错了什么吗?

还是得到的。即使我已经通过了 90 秒作为超时,但没有效果。 奇怪的是它确实有一段时间起作用了

我也得到了这个异常。 经过调查,默认情况下 HttpClient 等待响应标头 + 内容准备好用于所有方法,例如。PostAsync, SendAsync, GetAsync.因此,如果响应没有/无效的内容长度。您将收到此错误。看到这里。所以建议使用 SendAsync(xxx, HttpCompletionOption.ResponseHeadersRead(

using (var req = new HttpRequestMessage(HttpMethod.Post, url))
{
var body = File.ReadAllText("body.txt").Trim();
req.Content = new StringContent(body, Encoding.UTF8, "application/json-patch+json");
// the follow code throw exception
// System.IO.IOException: The response ended prematurely
// since 'HttpCompletionOption.ResponseContentRead' is the default behavior
// var response = await httpClient.SendAsync(req, HttpCompletionOption.ResponseContentRead);
var response = await httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
}

相关内容

最新更新