c# - HttpWebResponse 中永无止境的 Stream

标签 c# .net httpwebresponse

我怎样才能读取一些字节并断开连接?我用这样的代码

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/

相关文章:

c# - 短暂的对象

c# - 编码 C 结构,其中包含结构数组

.net - 如何通过 .Net 代码截取网站的屏幕截图?

c# - Linq最小日期最大日期模型查询

C# - httpWebRequest 流的大小是否有限制?

c# - 引导多个生产者和消费者

c# - IEnumerable 作为 DataTable 性能问题

asp.net - 重用 CookieContainer 时如何确定 session 超时

c# - 如何打开备用 Web 浏览器(Mozilla 或 Firefox)并显示特定 URL?

powershell httpwebrequest GET方法cookiecontainer有问题吗?