c# HttpWebRequest服务器没有返回完整的响应
本文关键字:响应 返回 HttpWebRequest 服务器 | 更新日期: 2023-09-27 18:18:57
我正在向返回带有数据的HTML的服务器发出HTTP请求。但有时它会在没有任何明确解释的情况下"中途停止"。例如响应结束:
[...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请求(调试)时,几乎没有网络延迟,一切都很好,但是当您在互联网上使用相同的代码时,服务器不会在一个块中发送所有响应数据,服务器可能忙于处理其他请求或可能存在一些网络延迟,然后,您接收响应数据在几个块中。
来自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;
}