You can't authenticate a user without providing credentials. Manually download the file once while inspecting the session with something like Fiddler. That will reveal the headers required for the POST
request. Then automate the request like this:
url = "http://..."
user = "..."
pass = "..."
credentials = "username=" & user & "&password=" & pass
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "POST", url, False
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.send credentials
Modify credentials
according to what Fiddler revealed. You may need to encode the values (user
and pass
in the example above) with something like this:
Function Encode(ByVal str)
Set re = New RegExp
re.Pattern = "[^a-zA-Z0-9_.~-]"
enc = ""
For i = 1 To Len(str)
c = Mid(str, i, 1)
If re.Test(c) Then c = "%" & Right("0" & Hex(Asc(c)), 2)
enc = enc & c
Next
Encode = enc
End Function
Save the responseBody
to a file like this:
filename = "C:\your\output.xls"
Set stream = CreateObject("ADODB.Stream")
If req.status = 200 Then
stream.Open
stream.Type = 1 'binary
stream.Write req.responseBody
stream.SaveToFile filename, 2
stream.Close
End If
If the filename is dynamically generated you may need to read the response and/or status text and send a second request to actually retrieve the file. However, that depends on the actual server response (as revealed by Fiddler).
Edit: A solution I found here suggests using a WinHttpRequest
object:
Set req = CreateObject("WinHttp.WinHttpRequest.5.1")
req.SetAutoLogonPolicy 0
req.Open "POST", url, False
req.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.Send credentials
I can't test this, though, because I don't have a web server using NTLM authentication at hand.