VBA WinHTTP从密码保护的https网站下载文件 - 保存的文件已损坏

时间:2017-01-26 18:44:51

标签: excel vba authentication https download

我已经通过Excel先生以及本网站的其他地方(特别是问题22051960,似乎对像我这样的新用户关闭)搜索了这个问题的解决方案。 我试图从中下载的网站是: https://downloads.theice.com/ 并且看起来主站点是一个请求授权凭证的html页面。

我已经尝试了上面引用的线程的代码,它似乎成功打开了主站点,验证并保存了文件;但是,当我导航到文件时,它不是网站上的文件,而是仅1kb而不是excel格式。以下是该主题的代码:

Sub SaveFileFromURL()

Dim FileNum As Long
Dim FileData() As Byte
Dim WHTTP As Object

mainUrl = "https://downloads.theice.com/"
fileUrl = "https://downloads.theice.com/Settlement_Reports/Oil/icecleared_oil_2017_01_24.xlsx"
filePath = "C:\mydownloads\myfile2.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

我在excel中有合理的vba技能,但没有html或网页功能的经验,因此如何解决此问题。 我的最终目标是在我编写的例程中使用身份验证代码,该例程自动保存excel电子表格中的URL列表中的文件,该电子表格已经适用于未受保护的URL。

我希望这个论坛是一个可以接受的问题 非常感谢

1 个答案:

答案 0 :(得分:0)

在我看来,您应该在SetCredentials实例上发送请求之前设置凭据(WinHttpRequest方法)。

像这样的东西

WHTTP.SetCredentials(myuser , mypass , HTTPREQUEST_SETCREDENTIALS_FOR_SERVER);

您还可以查看以下链接吗?

https://msdn.microsoft.com/en-us/library/aa384058(VS.85).aspx

https://msdn.microsoft.com/en-us/library/windows/desktop/aa383144(v=vs.85).aspx

https://msdn.microsoft.com/en-us/library/windows/desktop/aa384076(v=vs.85).aspx

我希望这会对你有所帮助