4

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?

Forivin
  • 14,780
  • 27
  • 106
  • 199
  • I think that your recent posts are very useful. Please post them at ahkscript.org – vasili111 Apr 05 '15 at 19:24
  • Thank you. :) You can already find most of them over there. They just tend to be hard to find, because not all of them have dedicated threads and some of them are on autohotkey.com and some are on ahkscript.org. I'm posting them under the name "Bruttosozialprodukt". For example: http://www.autohotkey.com/board/topic/101007-super-simple-download-with-progress-bar/#post_id_632780 – Forivin Apr 05 '15 at 19:31
  • There will be merge of autohotkey.com and ahkscript.org soon. Current autohotkey.com forum will become read only and forum that is at ahkscript.org will move to autohotkey.com and be active. You have really many nice and useful scripts and to make them easy searcheble I think it is better to make separate thread for every of them at ahkscript.org . – vasili111 Apr 06 '15 at 07:20

1 Answers1

3

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")
Forivin
  • 14,780
  • 27
  • 106
  • 199
  • Thanks a thousand times for your effort. Your contribution to the ahk network is very much welcomed :) – phil294 Apr 06 '15 at 10:41