VBA download form URL with login that redirect to another one

删除回忆录丶 提交于 2021-02-08 07:20:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!