【问题标题】:Cannot load page with either WebClient or HttpWebRequest无法使用 WebClient 或 HttpWebRequest 加载页面
【发布时间】:2017-02-20 22:56:10
【问题描述】:

无论我使用WebClient 还是HttpWebRequest,加载此页面都会超时。我究竟做错了什么?不能是https,因为其他https 网站加载正常。

下面是我最近的尝试,它添加了我在 Firefox 的检查器中看到的所有标题。

一个有趣的行为是我无法使用 Fiddler 监控这一点,因为 Fiddler 运行时一切正常。

    Using client As WebClient = New WebClient()
        client.Headers(HttpRequestHeader.Accept) = "text/html, image/png, image/jpeg, image/gif, */*;q=0.1"
        client.Headers(HttpRequestHeader.UserAgent) = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12"
        client.Headers(HttpRequestHeader.AcceptLanguage) = "en-US;en;q=0.5"
        client.Headers(HttpRequestHeader.AcceptEncoding) = "gzip, deflate, br"
        client.Headers(HttpRequestHeader.Referer) = "http://www.torontohydro.com/sites/electricsystem/Pages/foryourhome.aspx"
        client.Headers("DNT") = "1"
        client.Headers(HttpRequestHeader.KeepAlive) = "keep-alive"
        client.Headers(HttpRequestHeader.Upgrade) = "1"
        client.Headers(HttpRequestHeader.CacheControl) = "max-age=0"

        Dim x = New Uri("https://css.torontohydro.com/")
        Dim data as string = client.DownloadString(x)
    End Using

所有这些都是多余的代码。将其归结为仅几行会导致相同的挂起。

    Using client as WebClient = New WebClient()
        Dim data as string = client.DownloadString("https://css.torontohydro.com")
    End Using

简而言之,这就是HttpWebRequest 代码,它也挂起获取响应。

        Dim getRequest As HttpWebRequest = CreateWebRequest("https://css.torontohydro.com/")
        getRequest.CachePolicy = New Cache.RequestCachePolicy(Cache.RequestCacheLevel.BypassCache)

        Using webResponse As HttpWebResponse = CType(getRequest.GetResponse(), HttpWebResponse)
            'no need for any more code, since the above line is where things hang

【问题讨论】:

  • 为什么要为 VB.Net 代码道歉?
  • 你只是想要页面 html 吗?
  • 抱歉,我是在开玩笑。我有几页要阅读该网站,但甚至无法通过第一页。似乎是特定于网站的。无论我设置所有这些标题还是只使用最后两行,我都会得到相同的超时。或者,如果我使用 HttpWebRequestGET 方法。
  • 我让它通过 Firefox 中的 RESTClient 插件加载。你只是得到一个超时,没有其他特定的错误代码?您是否尝试过将其放入 try .. catch .. 块中并记录错误?
  • 这是一般try/catch 块中的超时异常。我无法使用任何 .NET 方法来加载页面。

标签: vb.net webclient


【解决方案1】:

所以这最终是由于该项目仍在 .NET 3.5 中。 .NET 尝试使用 SSL 加载站点,即https。添加此行解决了问题:

    ServicePointManager.SecurityProtocol = 3072

我不得不使用 3072,因为 3.5 不包含 SecurityProtocolType.Tls12 的定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多