HttpWebResponse返回“不完整"流 [英] HttpWebResponse returns an 'incomplete' stream
问题描述
我正在使用HttpWebRequest向Web服务器重复请求,但是作为回报,我随机获得了中断"响应流.例如,它不包含我知道"应该在那里的标签.如果我连续多次请求相同的页面,它将显示为破损"〜3/5.
I´m making repeated requests to a web server using HttpWebRequest, but I randomly get a 'broken' response stream in return. e.g it doesn´t contain the tags that I KNOW is supposed to be there. If I request the same page multiple times in a row it turns up 'broken' ~3/5.
请求始终返回200响应,因此我首先认为响应中插入了一个空值,使StreamReader认为它已到达末尾.
The request always returns a 200 response so I first thought there was a null value inserted in the response that made the StreamReader think it reached the end.
我尝试过: 1)将所有内容读入字节数组并进行清理 2)在每个请求之后插入一个随机的Thread.Sleep
I´ve tried: 1) reading everything into a byte array and cleaning it 2) inserting a random Thread.Sleep after each request
下面的代码是否存在任何潜在的不良做法,或者谁能告诉我为什么我随机得到一个不完整的响应流?据我所见,我正在关闭所有非托管资源,所以应该不会有问题,对吧?
Is there any potentially bad practice with my code below or can anyone tell me why I´m randomly getting an incomplete response stream? As far as I can see I´m closing all unmanaged resources so that shouldn´t be a problem, right?
public string ReturnHtmlResponse(string url)
{
string result;
var request = (HttpWebRequest)WebRequest.Create(url);
{
using(var response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine((int)response.StatusCode);
var encoding = Encoding.GetEncoding(response.CharacterSet);
using(var stream = response.GetResponseStream())
{
using(var sr = new StreamReader(stream,encoding))
{
result = sr.ReadToEnd();
}
}
}
}
return result;
}
推荐答案
我看不到代码中有任何直接缺陷.可能是父项" using语句之一在嵌套语句之前完成. 尝试将using更改为Dispose()和Close()方法.
I do not see any direct flaws in you're code. What could be is that one of the 'Parent' using statements is done before the nested one. Try changing the using to a Dispose() and Close() method.
public string ReturnHtmlResponse(string url)
{
string result;
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
Console.WriteLine((int)response.StatusCode);
var encoding = Encoding.GetEncoding(response.CharacterSet);
var stream = response.GetResponseStream();
var sr = new StreamReader(stream,encoding);
result = sr.ReadToEnd();
sr.Close();
stream.Close();
response.Close();
sr.Dispose();
stream.Dispose();
response.Dispose();
return result;
}
这篇关于HttpWebResponse返回“不完整"流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!