简体   繁体   English

永远不会在HttpWebResponse中结束Stream

[英]Never ending Stream in HttpWebResponse

how can i read some bytes and disconnect? 我怎样才能读取一些字节并断开连接? i use such code 我使用这样的代码

using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
    using (Stream sm = resp.GetResponseStream())
    {
        using (StreamReader sr = new StreamReader(sm, Encoding.Default))
        {
            sr.Read();
            sr.Close();
        }
    }
}

but it wait for end of stream 但它等待流的结束

You probably don't want to use a StreamReader to read a WebResonse stream unless you know for sure that the stream contains newlines. 您可能不希望使用StreamReader来读取WebResonse流,除非您确定该流包含换行符。 StreamReader likes to think in terms of lines, and if there aren't any newlines in the stream, it's going to hang. StreamReader喜欢用行来思考,如果流中没有任何换行符,它就会挂起。

Your best bet is to read as many bytes as you want into a byte[] buffer, and then convert that to text. 最好的办法是在byte[]缓冲区中读取所需的byte[] ,然后将其转换为文本。 For example: 例如:

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();
    }
}

At this point, the buffer has the first BYTES_TO_READ bytes from the buffer. 此时,缓冲区具有缓冲区中的第一个BYTES_TO_READ字节。 You can then convert that to a string, like this: 然后,您可以将其转换为字符串,如下所示:

string s = Encoding.Default.GetString(buffer);

Or you can open a MemoryStream on the buffer if you want to use StreamReader . 或者,如果要使用StreamReader可以在缓冲区上打开MemoryStream

I have run into WebResponse hanging sometimes if you don't read everything. 如果你没有阅读所有内容,我有时会遇到WebResponse I don't know why it does that, and I can't reliably reproduce it, but I've found that if I do request.Abort() before closing the stream, everything works. 我不知道它为什么这样做,我无法可靠地重现它,但我发现如果我在关闭流之前request.Abort() ,一切正常。 See 看到

On a side note, the word you want is "unresponsive" rather than "unresponsible." 另一方面,你想要的词是“反应迟钝”,而不是“不负责任”。

Could you do something like this? 你能做这样的事吗?

        string GetWebPageContent(string url)
        {
            string result = string.Empty;
            HttpWebRequest request;
            const int bytesToGet = 1000;
            request = WebRequest.Create(url) as HttpWebRequest;

//get first 1000 bytes
            request.AddRange(0, bytesToGet - 1);

            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
            }
            return result;
        }

The key is using AddRange in your request. 关键是在您的请求中使用AddRange

It is beacuse http 1.1 connection is persistent connection default and the tcp connection has not been closed,so the stream dose not receive the end. 它是因为http 1.1连接是持久连接默认而且tcp连接尚未关闭,所以流量不接收结束。

you can use myHttpWebRequest1.KeepAlive=false; 你可以使用myHttpWebRequest1.KeepAlive = false; so the tcp connection will close after the http reponse. 所以在http响应之后tcp连接将关闭。

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.connection(v=vs.110).aspx# https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.connection(v=vs.110).aspx#

If you talking winforms or webforms I would put the request into a threadpool (or Task if you are using .net 4). 如果您正在谈论winforms或webforms,我会将请求放入线程池(如果您使用的是.net 4,则为Task)。 Streams, even with a good handling, are too easy to put GUI in a wait-state that dislikes by most users. 即使具有良好的处理能力,流也很容易将GUI置于大多数用户不喜欢的等待状态。

I had similar never-ending request parsing with examples listed here. 我有类似的永不停止的请求解析与此处列出的示例。 The following is what I came up with to eliminate those issues: 以下是我提出的消除这些问题的方法:

// url is a string where the request is going.
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

// Do what you have to do with the Request.

StringBuilder builder = new StringBuilder();
int toRead = 1000;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    HttpStatusCode status = response.StatusCode;

    using (Stream receiveStream = response.GetResponseStream())
    {
        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.GetEncoding("utf-8")))
        {
            Char[] read = new Char[toRead];
            int count = readStream.Read(read, 0, toRead);

            while (count > 0)
            {
                string str = new String(read, 0, count);
                builder.Append(str);

                count = readStream.Read(read, 0, toRead);
            }

            readStream.Close();
        }   
    }

    response.Close();
}

return builder.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM