在某些域名我无法下载图片。代码正在与其他域一起使用,但有些域则没有。我无法弄清楚为什么。我可以使用像firefox或chrome这样的完整浏览器下载图像,但不能使用httpwebrequest下载。 我试图尽可能接近地模拟完整的浏览器,但没有成功。
也许你可以帮我找到错误?
错误是:
System.dll中发生System.Net.WebException异常错误。 附加信息:基础连接已关闭: 发送时出现意外错误
在线:
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
答案 0 :(得分:2)
在这种情况下,问题是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网络客户端不默认为:
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")