代码之家  ›  专栏  ›  技术社区  ›  memme

.net无法下载图像。请求被阻止,为什么?(httpwebrequest)

  •  1
  • memme  · 技术社区  · 7 年前

    在某些域上,我无法下载图像。该代码正在与其他域协同工作,但与一些its协同工作。我不知道为什么。我可以使用firefox或chrome等全浏览器下载图像,但不能使用httpwebrequest。 我试图尽可能近距离地模拟全浏览器,但没有成功。

    也许你能帮我找到错误?

    错误为:

    一个系统。网系统中发生WebException异常错误。dll。 其他信息:基础连接已关闭: 发送时出现意外错误

    在线:

        Dim httpWebResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
    

    以下是故障下载示例代码:

        Dim httpWebRequest = DirectCast(WebRequest.Create("https://www.oglf.org/wp-content/uploads/2017/12/BestLEDTeethWhitening.jpg"), HttpWebRequest)
        httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0"
        httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us,en;q=0.5")
        httpWebRequest.Referer = "https://www.oglf.org"
        httpWebRequest.AllowAutoRedirect = True
        httpWebRequest.KeepAlive = True
    
        Dim httpWebResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
    
        If (httpWebResponse.StatusCode <> HttpStatusCode.OK AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Moved AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Redirect) OrElse Not httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase) Then
            Return
        End If
        Using stream = httpWebResponse.GetResponseStream()
            Using fileStream = File.OpenWrite("c:\imagetest.jpg")
                Dim bytes = New Byte(4095) {}
                Dim read = 0
                Do
                    If stream Is Nothing Then
                        Continue Do
                    End If
                    read = stream.Read(bytes, 0, bytes.Length)
                    fileStream.Write(bytes, 0, read)
                Loop While read <> 0
            End Using
        End Using
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   soohoonigan    7 年前

    在这种情况下,问题是ssl连接协商失败。如果您不使用ssl进行连接对您没有任何影响,我只会使用以下方法:

    Private Sub DownloadImage(ByVal source As String, destination As String)
        If source.StartsWith("https://") Then source = source.Replace("https://", "http://")
        Using wc As New System.Net.WebClient
            wc.DownloadFile(source, destination)
        End Using
    End Sub
    

    如果必须使用ssl,请尝试将TLS版本设置为1.2,因为某些网站需要,并且。net web client不默认为:

    Private Sub DownloadImage(ByVal source As String, destination As String)
        System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls12
        Using wc As New System.Net.WebClient
            wc.DownloadFile(source, destination)
        End Using
    End Sub
    

    调用时使用:

    DownloadImage("https://www.oglf.org/wp-content/uploads/2017/12/BestLEDTeethWhitening.jpg", _
                  "c:/tmp/test.jpg")