0

我在加载网页时遇到问题。不知何故,我得到的响应似乎不完整,因为只显示了页面的第一部分。使用 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; }
}
4

1 回答 1

1

我认为您正在尝试加载 ajax 网页。

出现此问题的原因是因为httpwebrequest不理解 JavaScript 并且无法跟踪 JavaScript 以获取其中的网页。

要检查它,请转到您想要的网页并右键单击以查看源代码,在源代码中您找不到网页的缺失部分,但如果您使用的是 Chrome,您可以使用检查元素找出缺失的部分部分。然后它使用ajax。

请参阅此MSDN 线程

于 2012-08-14T15:21:56.620 回答