我怎样才能读取一些字节并断开连接?我用这样的代码
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
using (Stream sm = resp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(sm, Encoding.Default))
{
sr.Read();
sr.Close();
}
}
}
但它等待流结束
最佳答案
您可能不想使用 StreamReader
来读取 WebResonse
流,除非您确定该流包含换行符。 StreamReader
喜欢按行思考,如果流中没有任何换行符,它就会挂起。
最好的办法是将任意多的字节读入 byte[]
缓冲区,然后将其转换为文本。例如:
int BYTES_TO_READ = 1000;
var buffer = new byte[BYTES_TO_READ];
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
using (Stream sm = resp.GetResponseStream())
{
int totalBytesRead = 0;
int bytesRead;
do
{
// You have to do this in a loop because there's no guarantee that
// all the bytes you need will be ready when you call.
bytesRead = sm.Read(buffer, totalBytesRead, BYTES_TO_READ-totalBytesRead);
totalBytesRead += bytesRead;
} while (totalBytesRead < BYTES_TO_READ);
// Sometimes WebResponse will hang if you try to close before
// you've read the entire stream. So you can abort the request.
request.Abort();
}
}
此时,缓冲区具有缓冲区中的第一个 BYTES_TO_READ
个字节。然后您可以将其转换为字符串,如下所示:
string s = Encoding.Default.GetString(buffer);
或者,如果您想使用 StreamReader
,您可以在缓冲区上打开一个 MemoryStream
。
如果您不阅读所有内容,我有时会遇到 WebResponse
挂起的情况。我不知道它为什么这样做,而且我无法可靠地重现它,但我发现如果我在关闭流之前执行 request.Abort()
,一切正常。见
附带说明一下,您想要的词是“无响应”而不是“不负责任”。
关于c# - HttpWebResponse 中永无止境的 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205522/