问题
the website requires login then redirect you to other url then download the file
this function works fine with url with no redirction but not with my case
Function DownloadFile(URL As String, Path As String, UserName As String, Password As String) As Boolean
DownloadFile = False
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("MSXML2.ServerXMLHTTP.6.0")
WinHttpReq.Open "GET", URL, False, UserName, Password
WinHttpReq.send
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile Path, 2
oStream.Close
DownloadFile = True
End Function
when I try this code the status is 401 even that I use the username and password?
Function CheckStatus(ByVal strUrl As String, ByVal UserName As String, ByVal Password As String) As String
Const WinHttpRequestOption_EnableRedirects = 6
Dim oHttp As Object
Set oHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
oHttp.Option(WinHttpRequestOption_EnableRedirects) = True
oHttp.Open "GET", strUrl, False, UserName, Password
oHttp.send
CheckStatus = oHttp.Status
End Function
回答1:
WinHttp will follow the redirect by default. here is how to deal with username and password using WinHttp.
Function DownloadFile(ByVal URL As String, ByVal path As String, ByVal UserName As String, ByVal Password As String) As Boolean
DownloadFile = False
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Dim WinHttpReq As Object
Dim oStream As Object
Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
WinHttpReq.Open "GET", URL, False
WinHttpReq.SetCredentials UserName, Password, HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
WinHttpReq.send
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile path, 2
oStream.Close
DownloadFile = True
End Function
来源:https://stackoverflow.com/questions/59598416/vba-download-form-url-with-login-that-redirect-to-another-one