Alternative to UrlDownloadToFile

这一生的挚爱 提交于 2019-12-06 04:58:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!