我在加载网页时遇到问题。不知何故,我得到的响应似乎不完整,因为只显示了页面的第一部分。使用 ReadToEnd 写出响应流时,无论我尝试浏览哪个网页,它都只会在字符串中显示大约 700 个字符。请参阅下面的代码:
public class GetServerResponse
{
private Uri url;
public GetServerResponse(Uri uri)
{
this.url = uri;
HttpWebRequest h = (HttpWebRequest)WebRequest.Create(this.url);
StartRequest(this.url);
}
private void StartRequest(Uri url)
{
HttpWebRequest internalRequest = (HttpWebRequest)WebRequest.Create(url);
GetServerResponseState responseState = new GetServerResponseState();
responseState.AsyncRequest = internalRequest;
internalRequest.BeginGetResponse(new AsyncCallback(HandleServerResponse), responseState);
}
private void HandleServerResponse(IAsyncResult asyncResult)
{
GetServerResponseState responseState = (GetServerResponseState)asyncResult.AsyncState;
HttpWebRequest internalRequest = (HttpWebRequest)responseState.AsyncRequest;
internalRequest.AllowAutoRedirect = false;
responseState.AsyncResponse = (HttpWebResponse)internalRequest.EndGetResponse(asyncResult);
Stream streamResult;
try
{
streamResult = responseState.AsyncResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(streamResult, Encoding.UTF8))
{
System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
}
}
catch (FormatException)
{
return;
}
}
}
public class GetServerResponseState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}