我正在尝试使用VBA来测试URL中的坏链接和重定向。
对于通过VBA使用MSXML2或WinHttp库返回3xx系列.Status响应的URL,我可以使用HTTP request GET方法获得重定向URL。
当我尝试对某些具有合法(由URL站点指定的)重定向的URL使用此方法时,在尝试获取请求对象时收到一个错误。
例如,当在浏览器中输入以下网址时:http://www.teconnectivity.com ...the浏览器最终将到达此地址:http://www.te.com/en/home.html
但是,此VBA代码将返回错误-2147012744:“服务器返回无效或无法识别的响应”。在.Send语句中抛出错误。
Sub Test()
Debug.Print sGetRedirectURL("http://www.teconnectivity.com/")
End Sub
Private Function sGetRedirectURL(ByVal sURL As String) As String
Dim oRequest As WinHttp.WinHttpRequest
Dim sReturn As String
Set oRequest = New WinHttp.WinHttpRequest
On Error GoTo ErrProc
With oRequest
.Option(WinHttpRequestOption_EnableRedirects) = False
.Open "GET", sURL, False
.Send
If Left$(.Status, 1) = "3" Then
sReturn = .GetResponseHeader("Location")
End If
End With
On Error GoTo 0
ExitProc:
sGetRedirectURL = sReturn
Exit Function
ErrProc:
Debug.Print Err.Number & ": " & Err.Description
Resume ExitProc
End Function
如果带有该http://www.te.com/en/home.html的HTTP请求返回错误,我的浏览器如何能够到达目的地: URL?
我可以使用浏览器的应用程序来获得最终的目的地URL,如下所示:
Function sGetFinalURL(sURL As String) As String
Dim oAppIE As Object
Dim sReturn As String
Set oAppIE = CreateObject("InternetExplorer.Application")
With oAppIE
.Navigate sURL
Do While .Busy
Loop
sReturn = .document.url
.Quit
End With
Set oAppIE = Nothing
sGetFinalURL = sReturn
End Function
但是,该方法还将返回ISP重定向或其他劫持的URL。
发布于 2015-05-04 08:29:37
我最终采用的方法是使用浏览器应用程序尝试导航到一个不存在的域URL。如果浏览器到达某个URL,则意味着该URL已被ISP或不存在的域以外的其他域名重定向。
Private Function sGetNXDomainRedirect() As String
'--attempts to return the domain used to redirect non-existant
' domain urls. Used to distinguish legitimate redirects
' from ISP redirects or other hijacks
'--returns "NoRedirect" if the bogus url is not redirected.
Dim sReturn As String
Dim oIEapp As Object
Dim uTest As udtHttpInfo
Const sBOGUS_URL As String = _
"http://wwXYXw.NXDomainToTest"
Set oIEapp = CreateObject("InternetExplorer.Application")
With oIEapp
.Navigate sBOGUS_URL
Do While .Busy
Loop
On Error Resume Next
sReturn = .document.Domain
On Error GoTo 0
.Quit
End With
Set oIEapp = Nothing
If Len(sReturn) = 0 Then sReturn = "NoRedirect"
sGetNXDomainRedirect = sReturn
End Function
Link to complete code on MrExcel.com forum
一旦知道了"ISP重定向“站点,就可以使用IE应用程序来测试坏链接或合法重定向。如果通过IE应用程序导航返回的域不是ISP重定向域,则我将其解释为合法重定向。
https://stackoverflow.com/questions/29882950
复制相似问题