繁体   English   中英

C#HttpWebRequest服务器未返回完整响应

[英]C# HttpWebRequest Server not returning full response

我正在向服务器返回HTTP请求,该服务器返回带有数据的HTML。 但是有时它“停在中间”而没有任何明确的解释。 例如,响应结束:

[...Content length 14336 chars ...]</tbody></table><p /><br /><ul id=

它只是在生成HTML的过程中停止。 我的代码:

var request = (HttpWebRequest) WebRequest.Create("http://example.com);
var authInfo = string.Format("{0}:{1}", "username", "password");
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
request.Credentials = new NetworkCredential(user.Xname, decryptedPassword);
request.Method = WebRequestMethods.Http.Get;
request.AllowAutoRedirect = true;
request.Proxy = null;
var response = (HttpWebResponse) request.GetResponse();
var stream = response.GetResponseStream();
var streamreader = new StreamReader(stream, Encoding.GetEncoding("ISO-8859-2"));
var s = streamreader.ReadToEnd();

代码是否不等到最后才有可能?

当您在本地执行http Web请求(调试)时,几乎没有网络延迟,一切都很好,但是,当您在Internet上使用相同的代码时,服务器未将所有响应数据发送到一个块中,服务器可能正在忙于处理其他数据请求,或者可能存在一些网络延迟,那么您会分几块接收响应数据。

当您将第一个数据块接收到流中时,StreamReader的ReadToEnd方法将仅读取可用数据,而无需等待其他数据。

这并不意味着响应已完成,并且您已收到所有响应数据,互联网上某处找到的下一个代码可以正确处理读取过程...(该代码不是我的,因此我无法获得荣誉)

    public static byte[] ReadFully(Stream stream, int initialLength)
    {
        // If we've been passed an unhelpful initial length, just
        // use 32K.
        if (initialLength < 1)
        {
            initialLength = 32768;
        }


        byte[] buffer = new byte[initialLength];
        int read = 0;


        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
            read += chunk;


            // If we've reached the end of our buffer, check to see if there's
            // any more information
            if (read == buffer.Length)
            {
                int nextByte = stream.ReadByte();


                // End of stream? If so, we're done
                if (nextByte == -1)
                {
                    return buffer;
                }


                // Nope. Resize the buffer, put in the byte we've just
                // read, and continue
                byte[] newBuffer = new byte[buffer.Length * 2];
                Array.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (byte)nextByte;
                buffer = newBuffer;
                read++;
            }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
    }

暂无
暂无

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

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