DownloadString超时

Zol*_*han 2 c# asp.net

我有一个返回网页内容的方法:

        private string FetchHTML(string sUrl, Encoding encoding)
        {
            System.Net.WebClient oClient = new System.Net.WebClient();
            oClient.Encoding = encoding;
            return System.Web.HttpUtility.HtmlDecode(oClient.DownloadString(sUrl));
        }
Run Code Online (Sandbox Code Playgroud)

但是当我尝试从livejournal加载链接时(例如,http: //mos-jkh.livejournal.com/769579.html ),我在DownloadString上收到此异常:

请求已中止:操作已超时.

这是一个已知的问题吗?为什么DownloadString不适用于某些网页,是否有解决方案?或者有替代DownloadString?

Zol*_*han 8

有些网站足够聪明,可以检查请求是否是由浏览器发出的.当他们发现请求不是通过浏览器完成时,他们没有响应.但是通过简单地发送带有请求的用户代理信息就很容易欺骗他们.所以解决方案是在FetchHTML方法中添加一行代码:

    private string FetchHTML(string sUrl, Encoding encoding)
    {
        System.Net.WebClient oClient = new System.Net.WebClient();
        oClient.Encoding = encoding;
        // set the user agent to IE6
        oClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
        return System.Web.HttpUtility.HtmlDecode(oClient.DownloadString(sUrl));
    }
Run Code Online (Sandbox Code Playgroud)

PS:为了发现问题,我使用的是Fiddler而不是Wireshark,我发现它太复杂了.