问题
UrlDownloadToFile is a nice command in AutoHotkey and works just fine, most of the time, but sometimes a download mechanism is too complex for it. For example if the download requires a specific user-agent to be set or if the download requires a cookie or maybe even a password.
So the question is:
Is there a more advanced download function, which could handle all of the above said?
回答1:
I wrote this quite some time ago and thought it would be a nice idea to wrap it up in a function and post it here:
Download(UrlToFile,SaveFileAs:="",Overwrite:=True,headers:="",method:="GET",postData:="") {
WinHttpObj := ComObjCreate("WinHttp.WinHttpRequest.5.1")
WinHttpObj.Open(method, UrlToFile)
For header, value in headers
WinHttpObj.SetRequestHeader(header, value)
WinHttpObj.Send(postData)
ADODBObj := ComObjCreate("ADODB.Stream")
ADODBObj.Type := 1
ADODBObj.Open()
ADODBObj.Write(WinHttpObj.ResponseBody)
If !SaveFileAs {
urlSplitArray := StrSplit(UrlToFile, "/")
SaveFileAs := urlSplitArray[urlSplitArray.MaxIndex()]
}
ADODBObj.SaveToFile(SaveFileAs, Overwrite ? 2:1)
ADODBObj.Close()
}
Example 1
Download("http://ahkscript.org/download/1.1/AutoHotkey111402_Install.exe")
Example 2
customHeaders := {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0"
,"Cache-Control": "max-age=0"
,"Cookie": "downloadtoken=b82416fdb23e421fb5a"}
Download("http://download.piriform.com/ccsetup410.exe","",True,customHeaders)
Example 3
Download("http://foo.bar/example.exe","example.exe",True,{"Cookie":"sessionid=abc123"},"POST","username=foo_bar&password=qwerty")
来源:https://stackoverflow.com/questions/29460945/alternative-to-urldownloadtofile