I am trying to save a file from a password protected https site using WinHTTP. Here is the code:
Sub SaveFileFromURL()
Dim FileNum As Long
Dim FileData() As Byte
Dim WHTTP As Object
fileUrl = "https://www.website.com/dir1/dir2/file.xls"
filePath = "C:\myfile.xls"
myuser = "username"
mypass = "password"
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
WHTTP.Open "GET", fileUrl, False
WHTTP.SetCredentials myuser, mypass, HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
WHTTP.Send
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
Open filePath For Binary Access Write As
Put
Close
MsgBox "File has been saved!", vbInformation, "Success"
End Sub
The problem is authentication. The file is saved, but when I open it in Excel, it is just a html login page instead of the actual file. If I copy the direct url file and paste it into the address bar of the browser and I don’t enter the web page, the effect will be the same. I am presented with a login page. Then, if I enter my login and password, a download window will open, allowing me to save the file.
So, I think that part of the SetCredentials code does not work properly if I debug.print WHTTP.ResponseBody is html code instead of the data of the acutal file.
Is there a way to pass the userid and password for WinHTTP so that I can save the file correctly?
:
https:
======================= EDIT: ====================== ==
, , , . . :
Sub SaveFileFromURL()
Dim FileNum As Long
Dim FileData() As Byte
Dim WHTTP As Object
fileUrl = "https://www.website.com/dir1/dir2/file.xls"
filePath = "C:\myfile.xls"
myuser = "username"
mypass = "password"
strAuthenticate = "start-url=%2F&user=" & myuser & "&password=" & mypass & "&switch=Log+In"
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
WHTTP.Open "POST", fileUrl, False
WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.Send strAuthenticate
WHTTP.Open "GET", fileUrl, False
WHTTP.Send
Debug.Print WHTTP.GetAllResponseHeaders()
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
Open filePath For Binary Access Write As
Put
Close
MsgBox "File has been saved!", vbInformation, "Success"
End Sub
Debug.Print WHTTP.GetAllResponseHeaders() , :
Accept-Ranges: bytes
Content-Disposition: attachement; filename="xxx"
Content-Length: xxxxxx
Content-Type: application/octet-stream
, , , . :
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
Open filePath For Binary Access Write As
Put
Close
- - html, .
, ? ?