VBA WinHTTP to download file from password proteced https website

后端 未结 1 1029
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 09:07

I\'m trying to save a file from https password protected site using WinHTTP. Here\'s the code:

Sub SaveFileFromURL()

Dim FileNum As Long
Dim FileData() As B         


        
相关标签:
1条回答
  • 2020-11-29 09:27

    Ok, I did it. Here the code:

    Sub SaveFileFromURL()
    
    Dim FileNum As Long
    Dim FileData() As Byte
    Dim WHTTP As Object
    
    mainUrl = "https://www.website.com/"
    fileUrl = "https://www.website.com/dir1/dir2/file.xls"
    filePath = "C:\myfile.xls"
    
    myuser = "username"
    mypass = "password"
    
    '@David Zemens, I got this by examining webpage code using Chrome, thanks!
    strAuthenticate = "start-url=%2F&user=" & myuser & "&password=" & mypass & "&switch=Log+In"
    
    Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
    
    'I figured out that you have to POST authentication string to the main website address not to the direct file address
    WHTTP.Open "POST", mainUrl, False 'WHTTP.Open "POST", fileUrl, False
    WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    WHTTP.Send strAuthenticate
    
    'Then you have to GET direct file url
    WHTTP.Open "GET", fileUrl, False
    WHTTP.Send
    
    FileData = WHTTP.ResponseBody
    Set WHTTP = Nothing
    
    'Save the file
    FileNum = FreeFile
    Open filePath For Binary Access Write As #FileNum
        Put #FileNum, 1, FileData
    Close #FileNum
    
    MsgBox "File has been saved!", vbInformation, "Success"
    
    End Sub
    

    Thanks for all your help.

    BTW I've found this posts very useful:

    http://www.mrexcel.com/forum/excel-questions/353006-download-file-excel.html

    Not understanding why WinHTTP does NOT authenticate certain HTTPS resource

    How to parse line by line WinHTTP response: UTF-8 encoded CSV?

    0 讨论(0)
提交回复
热议问题