Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

[function] httpQuery GET and POST requests - update 0.3.6


  • Please log in to reply
94 replies to this topic

Poll: Should a more generic function be released which will include the already available web functions, such as header queries, uri encoding, base encoding, etc ? (144 member(s) have cast votes)

Should a more generic function be released which will include the already available web functions, such as header queries, uri encoding, base encoding, etc ?

  1. yes, i'd like to have one function to get all neccessary http functionalities in one instead of collecting each for my own (160 votes [96.39%])

    Percentage of vote: 96.39%

  2. no, i prefer collecting the functions i need (5 votes [3.01%])

    Percentage of vote: 3.01%

  3. neither nor ... explained in post (1 votes [0.60%])

    Percentage of vote: 0.60%

Vote Guests cannot vote
jeff_sundx
  • Members
  • 1 posts
  • Last active: Jan 08 2010 01:33 PM
  • Joined: 26 Feb 2009
Hi,

In you sample III, there's one error occurred if we run the script.

>>> if (write_bin(data,"ahk.exe",length)!=1)

it seems to be revised as

>>> if (write_bin(data,"ahk.zip",length)!=1)

if it named as ahk.exe and after downloading, the exe file appears and you cannot run it. At least in my computer cannot run. ;-)

httpquery.ahk is perfect! Thanks

Jeff

  • Guests
  • Last active:
  • Joined: --
Hi guys, I'm trying to get the download example to use a progress meter instead of the tooltip but I just can't get it to work any one got any ideas?

; exmpl.downloadBinary.httpQuery.ahk
; This example downloads the latest AHK environment and stores
; the received binary data to a file.
#noenv
data     := ""
URL      := "http://www.autohotkey.net/programs/AutoHotkey104706.zip"
httpQueryOps := "updateSize"
;SetTimer,Progress,10
length   := httpQuery(data,URL)
Gui, Add, Progress, section vProgress, x2 y2 w470 h10 , 25
; Generated using SmartGUI Creator 4.0
Gui, Show, x341 y250 h20 w479, New GUI Window
Return

;Tooltip
;if (write_bin(data,"AutoHotkey104706.zip",length)!=1)
;   MsgBox "There was an Error!"
;else
;   MsgBox ASX Source downloaded
;Return

numprogess, %HttpQueryCurrentSize% "/" %HttpQueryFullSize%


GuiControl,, Progress, ++%numprogress%
;showSize:
;   Tooltip,% HttpQueryCurrentSize "/" HttpQueryFullSize
;return

GuiClose:
GuiEscape:
   ExitApp

write_bin(byref bin,filename,size){
   h := DllCall("CreateFile","str",filename,"Uint",0x40000000
            ,"Uint",0,"UInt",0,"UInt",4,"Uint",0,"UInt",0)
   IfEqual h,-1, SetEnv, ErrorLevel, -1
   IfNotEqual ErrorLevel,0,ExitApp ; couldn't create the file
   r := DllCall("SetFilePointerEx","Uint",h,"Int64",0,"UInt *",p,"Int",0)
   IfEqual r,0, SetEnv, ErrorLevel, -3
   IfNotEqual ErrorLevel,0, {
      t = %ErrorLevel%              ; save ErrorLevel to be returned
      DllCall("CloseHandle", "Uint", h)
      ErrorLevel = %t%              ; return seek error
   }
   result := DllCall("WriteFile","UInt",h,"Str",bin,"UInt"
               ,size,"UInt *",Written,"UInt",0)
   h := DllCall("CloseHandle", "Uint", h)
   return, 1
}

#include httpQuery.ahk


IsNull
  • Moderators
  • 990 posts
  • Last active: May 15 2014 11:56 AM
  • Joined: 10 May 2007
numprogess, %HttpQueryCurrentSize% "/" %HttpQueryFullSize%
what's numprogress?


You may want to look at this script I've made a while ago: <!-- m -->http://de.autohotkey... ... t=download<!-- m -->

I've made it with support of this Library...

  • Guests
  • Last active:
  • Joined: --
Thanks for the reply, but when I use the example you gave, I don't get the status bar to move?

; exmpl.downloadBinary.httpQuery.ahk
; This example downloads the latest AHK environment and stores
; the received binary data to a file.
#noenv
data     := ""
URL      := "http://www.autohotkey.net/programs/AutoHotkey104706.zip"
httpQueryOps := "updateSize"
;SetTimer,Progress,10
length   := httpQuery(data,URL)
Gui, Add, Progress, section vProgress, x2 y2 w470 h10 , 25
; Generated using SmartGUI Creator 4.0
Gui, Show, x341 y250 h20 w479, New GUI Window
Return

;Tooltip
;if (write_bin(data,"AutoHotkey104706.zip",length)!=1)
;   MsgBox "There was an Error!"
;else
;   MsgBox ASX Source downloaded
;Return

progess, %HttpQueryCurrentSize% "/" %HttpQueryFullSize%


GuiControl,, Progress, ++%progress%

;showSize:
;   Tooltip,% HttpQueryCurrentSize "/" HttpQueryFullSize
;return

GuiClose:
GuiEscape:
   ExitApp

write_bin(byref bin,filename,size){
   h := DllCall("CreateFile","str",filename,"Uint",0x40000000
            ,"Uint",0,"UInt",0,"UInt",4,"Uint",0,"UInt",0)
   IfEqual h,-1, SetEnv, ErrorLevel, -1
   IfNotEqual ErrorLevel,0,ExitApp ; couldn't create the file
   r := DllCall("SetFilePointerEx","Uint",h,"Int64",0,"UInt *",p,"Int",0)
   IfEqual r,0, SetEnv, ErrorLevel, -3
   IfNotEqual ErrorLevel,0, {
      t = %ErrorLevel%              ; save ErrorLevel to be returned
      DllCall("CloseHandle", "Uint", h)
      ErrorLevel = %t%              ; return seek error
   }
   result := DllCall("WriteFile","UInt",h,"Str",bin,"UInt"
               ,size,"UInt *",Written,"UInt",0)
   h := DllCall("CloseHandle", "Uint", h)
   return, 1
}

#include httpQuery.ahk

I may just have to give up with the progress bar idea.

Voltron43
  • Members
  • 76 posts
  • Last active: May 06 2011 07:48 PM
  • Joined: 27 Mar 2009
I was finally able to get httpQuery to pass through my work's proxy server. Below is a modified version of Example I using Laszlo's Base64 converter.

Example I Modified:
; exmpl.searchAHKforum.httpQuery.ahk
; Searches the forum for a given Phrase: in this case httpQuery
#noenv
[color=red]StringCaseSense On
Chars = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

Proxy_UserName := ""
Proxy_Password := ""
Proxy_Address  := ""
Proxy_Port	  := ""[/color]

html      		:= ""
URL       		:= "http://www.autohotkey.com/forum/search.php?mode=results"
POSTData  		:= "search_keywords=httpQuery&search_terms=all&search_forum=-1&"
				     . "search_time=0&search_fields=all&show_results=topics&return_chars=500"
				     . "&sort_by=0&sort_dir=DESC"
[color=red]header 	  	 := "Proxy-Authorization: Basic " Base64(Proxy_UserName ":" Proxy_Password)
httpProxy 		:= Proxy_Address ":" Proxy_Port[/color]

length := httpQuery(html,URL,POSTdata,header)
varSetCapacity(html,-1)

Gui,Add,Edit,w600 +Wrap r25,% html
Gui,Show
Return

GuiClose:
GuiEscape:
   ExitApp

#Include httpQuery.ahk

; ------------------------------------------------------------------------------
; http://www.autohotkey.com/forum/viewtopic.php?t=5896

Base64(string)
{
   Loop Parse, string
   {
      If Mod(A_Index,3) = 1
         buffer := Asc(A_LoopField) << 16
      Else If Mod(A_Index,3) = 2
         buffer += Asc(A_LoopField) << 8
      Else {
         buffer += Asc(A_LoopField)
         out := out . Code(buffer>>18) . Code(buffer>>12) . Code(buffer>>6) . Code(buffer)
      }
   }
   If Mod(StrLen(string),3) = 0
      Return out
   If Mod(StrLen(string),3) = 1
      Return out . Code(buffer>>18) . Code(buffer>>12) "=="
   Return out . Code(buffer>>18) . Code(buffer>>12) . Code(buffer>>6) "="
}

InvBase64(code)
{
   StringReplace code, code, =,,All
   Loop Parse, code
   {
      If Mod(A_Index,4) = 1
         buffer := DeCode(A_LoopField) << 18
      Else If Mod(A_Index,4) = 2
         buffer += DeCode(A_LoopField) << 12
      Else If Mod(A_Index,4) = 3
         buffer += DeCode(A_LoopField) << 6
      Else {
         buffer += DeCode(A_LoopField)
         out := out . Chr(buffer>>16) . Chr(255 & buffer>>8) . Chr(255 & buffer)
      }
   }
   If Mod(StrLen(code),4) = 0
      Return out
   If Mod(StrLen(code),4) = 2
      Return out . Chr(buffer>>16)
   Return out . Chr(buffer>>16) . Chr(255 & buffer>>8)
}

Code(i)     ; <== Chars[i & 63], 0-base index
{
   Global Chars
   StringMid i, Chars, (i&63)+1, 1
   Return i
}

DeCode(c)   ; c = a char in Chars ==> position [0,63]
{
   Global Chars
   Return InStr(Chars,c,1) - 1
}


wakewatcher
  • Members
  • 254 posts
  • Last active: Oct 04 2011 10:03 PM
  • Joined: 15 Jul 2006
I'm trying to use httpQuery to interact and upload files to Amazon's S3 Service. I've got the web side page working but am having problems with the POSTdata variables for httpQuery (and indeed maybe its not even possible to do.) Rather than being more of a distraction here I've started a new topic. http://www.autohotke...ic.php?p=272543 Thanks for any help on this.

tank
  • Moderators
  • 4227 posts
  • Last active: Yesterday, 06:52 PM
  • Joined: 21 Dec 2007
COM_CoInitialize()
   URL:="http://wakewatcher.redirect.hm/sandbox/SendVidS3.php"
   file=C:\blah blah.blah
   PostData:="file=" file  ; for this post i truncated all of your hiden form data as it didnt show properly in this control however its just each key pare separated y a "[b]&[/b]"
   objHTTP := COM_ActiveXObject("Microsoft.XMLHTTP")
   COM_Invoke(objHTTP,"open","POST",URL,false)
   COM_Invoke(objHTTP,"setRequestHeader","Content-Type","text/html; charset=UTF-8")
   COM_Invoke(objHTTP,"send",PostData)
   loop,500
      If    COM_Invoke(objHTTP,"readystate") = 4
         Break
      Else sleep 500
   Gui,Add,Edit,w800 h600, % COM_Invoke(objHTTP,"responseText")
   COM_CoUninitialize() 
   Gui,Show
   return

   GuiClose:
   GuiEscape:
   COM_CoUninitialize() 
   ExitApp
i get the following to work with other form uploaders but your key seems to not play nice so i am at a loss here its all about the key at this point

wakewatcher
  • Members
  • 254 posts
  • Last active: Oct 04 2011 10:03 PM
  • Joined: 15 Jul 2006
tank, Once again thanks for looking at this thorny problem.

One thing to notice is that the actual form which uploads uses a different URL and not the SendVidS3.php URL. A tricky bit about this is that it's the SendVidS3 page that generates the encoded S3 policy and signature, then the form calls the Amazon http"s" S3 site. I've verified that the returned policy and signatures work as I've plugged them into the form manually and it all works. Here is the test url which allows cut and paste the policy etc into the form before submitting it.
http://wakewatcher.redirect.hm/sandbox/SendVidS3T.php
So what I thought is a call to SendVidS3.php to return then the policy and the signature and then package that up to an actual post to the s3 site.

To find out what the actual POST string would look like I did another test page this time changing the POST method to a GET method.

<form action=" https://autohotkey.s3.amazonaws.com/" method="get" enctype="multipart/form-data">
      <input type="hidden" name="key" value="folder/${filename}">
      <input type="hidden" name="AWSAccessKeyId" value="19SPCQ42SZ55Y0GM3JG2">
      <input type="hidden" name="acl" value="public-read">
      <input type="hidden" name="success_action_redirect" value=" http://wakewatcher.redirect.hm/sandbox/SendVidS3.php">
      <input type="hidden" name="policy" value="ugly policy string">
      <input type="hidden" name="signature" value="wQOtadvgLZxUvqTiiIctPO3m8VM=">
      <input type="hidden" name="Content-Disposition" value="attachment; filename=${filename}">
      <input type="hidden" name="Content-Type" id="Content-Type" value="video/mp4">      

      File to upload to S3 (size limit 50kb):
      <input name="file" id="file" type="file">
      <br/><br/> 
      <input type="submit" value="Upload File to S3">
    </form>
This of course is not what the S3 site is looking for but what it does do is generate the (ugly) query string. So putting it all together I tried this ahk script.

loop:
FileSelectFile,filename,,Pick a File which is less than 50K

POSTdata := "policy=Y"
URL = http://www.wakewatcher.redirect.hm/sandbox/SendVidS3.php
WININET_Init()
result := UrlGetContents(URL,"","",POSTdata)

stringgetpos,pos,result,%A_Space%
stringtrimright,policyDoc64,result,% length - pos
stringtrimleft,sigPolicyDoc,result,% Pos + 1

msgbox % "policyDoc64:`n" . policyDoc64 . "`n`nsigPolicyDoc:`n" . sigPolicyDoc

/*  Logical approach direct from form but decided to use 'get' results instead.
POSTdata = key=folder/${filename}
POSTdata = %POSTdata%&AWSAccessKeyId=19SPCQ42SZ55Y0GM3JG2
POSTdata = %POSTdata%&success_action_redirect=http://www.wakewatcher.redirect.hm/sandbox/SendVidS3.php
POSTdata = %POSTdata%&policy=%policyDoc64%
POSTdata = %POSTdata%&signature=%sigPolicyDoc%
POSTdata = %POSTdata%&Content-Disposition=attachment`; filename=${filename}
POSTdata = %POSTdata%&Content-Type=video/mp4
POSTdata = %POSTdata%&file=%filename%
*/

; built this up by cutting and pasting "GET method" results
POSTdata = key=folder`%2F`%24{filename}
POSTdata = %POSTdata%&AWSAccessKeyId=19SPCQ42SZ55Y0GM3JG2
POSTdata = %POSTdata%&acl=public-read
POSTdata = %POSTdata%&success_action_redirect=+http`%3A`%2F`%2Fwakewatcher.redirect.hm`%2Fsandbox`%2FSendVidS3.php ;not sure why it's +http and not just http
POSTdata = %POSTdata%&policy=%policyDoc64%
POSTdata = %POSTdata%&signature=%sigPolicyDoc%
POSTdata = %POSTdata%&Content-Disposition=attachment`%3B+filename`%3D`%24{filename}  ;not sure why it's +filename and not just filename
POSTdata = %POSTdata%&Content-Type=video`%2Fmp4
POSTdata = %POSTdata%&file=%filename%

URL = https://autohotkey.s3.amazonaws.com/  ;notice url is https not http
msgbox % UrlGetContents(URL,"","",POSTdata)
WININET_UnInit()
goto Loop
Return
#include ahklerner cool stuff
But this doesn't work as I get the response from UrlGetContents():

Bucket POST must be of the enclosure-type multipart/form-data

So after all this I should have asked does what you just tried work with https sites as well as http sites? Thanks again.

tank
  • Moderators
  • 4227 posts
  • Last active: Yesterday, 06:52 PM
  • Joined: 21 Dec 2007

So after all this I should have asked does what you just tried work with https sites as well as http sites? Thanks again.

Yes i do it fairly often here is my final for now attempt
EDIT: I lied aparently i do send a query string using post method to prevent caching
COM_CoInitialize()
FileDelete,%A_ScriptDir%\output.htm
URL1:="http://wakewatcher.redirect.hm/sandbox/SendVidS3T.php"
URL2:="https://autohotkey.s3.amazonaws.com" 
file=%A_ScriptDir%\output.htm
FileAppend,% t:=getPageSource(URL1),%A_ScriptDir%\output.htm
tt:=COM_Invoke(doc:=Txt2Doc(t),"all[4].innerHTML")
policyDoc64:=SubStr(tt,21,InStr(tt,"<br>",0,21)-21)
string:=SubStr(tt,InStr(tt,"sigPolicyDoc:<BR>")+17)
sigPolicyDoc:=SubStr(string,1,InStr(string,"<BR>")-1)
POSTdata = key=folder`%2F`%24{filename} 
POSTdata = %POSTdata%&AWSAccessKeyId=19SPCQ42SZ55Y0GM3JG2 
POSTdata = %POSTdata%&acl=public-read 
POSTdata = %POSTdata%&success_action_redirect=+http`%3A`%2F`%2Fwakewatcher.redirect.hm`%2Fsandbox`%2FSendVidS3.php ;not sure why it's +http and not just http 
POSTdata = %POSTdata%&policy=%policyDoc64% 
POSTdata = %POSTdata%&signature=%sigPolicyDoc% 
POSTdata = %POSTdata%&Content-Disposition=attachment`%3B+filename`%3D`%24{filename}  ;not sure why it's +filename and not just filename 
POSTdata = %POSTdata%&Content-Type=video`%2Fmp4 
POSTdata = %POSTdata%&file=%file%
FileAppend,% getPageSource(URL2,POSTdata),%A_ScriptDir%\output.htm
Run,%A_ScriptDir%\output.htm
COM_CoUninitialize() 
ExitApp
getPageSource(URL,Post="")
{
   objHTTP := COM_ActiveXObject("Microsoft.XMLHTTP")
   COM_Invoke(objHTTP,"open","Post",URL,false)
   COM_Invoke(objHTTP,"setRequestHeader","Content-Type","multipart/form-data") 
   COM_Invoke(objHTTP,"send",PostData)
   loop,500
      If    COM_Invoke(objHTTP,"readystate") = 4
         Break
      Else sleep 500
   Return COM_Invoke(objHTTP,"responseText")
}

Txt2Doc(t)
{
	doc := COM_CreateObject("{25336920-03F9-11CF-8FD0-00AA00686F13}") 
	COM_Invoke(doc, "write", t) 
	COM_Invoke(doc, "close") 
	Return doc
}
it fails as well but i am sure i am accurately getting your values though you seem to have edited the form since this morning

tank
  • Moderators
  • 4227 posts
  • Last active: Yesterday, 06:52 PM
  • Joined: 21 Dec 2007

you seem to have edited the form since this morning

and another darn thing if you have PHP at your beck and call why dont you just not create the form after all and use soemthing like this
<?php

$host = "www.example.com";

$path = "/path/to/script.php";

$file=$_REQUEST['file']; // send the file to the page via query string

$data = "data1=value1&data2=value2"; // put your actual un encoded key pares here

$data = urlencode($data);



header("POST $path HTTP/1.1\r\n" );

header("Host: $host\r\n" );

header("Content-type: multipart/form-data\r\n" );

header("Content-length: " . strlen($data) . "\r\n" );

header("Connection: close\r\n\r\n" );

header($data);

?>
of course you will have to modify it but seriously pass the dang filename to your own page in a query string and let PHP do what it not ahk was designed for. why are you using an a propane torch to hammer a nail any how

wakewatcher
  • Members
  • 254 posts
  • Last active: Oct 04 2011 10:03 PM
  • Joined: 15 Jul 2006
I'm persistent, not bright. :( (But you have to give me credit for trying...Everything!)

I'll have to figure out what you just did there. The bottom line is I have to use that form (or emulate that form) to send off the request to Amazon.

Thanks again for all the tips.

tank
  • Moderators
  • 4227 posts
  • Last active: Yesterday, 06:52 PM
  • Joined: 21 Dec 2007
the php i posted is an example and if you will just modify it with your url and data should do the trick and then a query string with your file to this php page when its complete
of all the languages i use it is far easier to manipulate headers and send post data with php than anything else

woonsik
  • Members
  • 15 posts
  • Last active: Apr 12 2013 08:32 AM
  • Joined: 15 Jan 2013

where is link httpQuery.ahk?



Guest10
  • Members
  • 982 posts
  • Last active: Today, 06:02 AM
  • Joined: 27 Oct 2012

does httpQuery-0-3-6.ahk work with AHK 1.1.9.2? the provided examples on page 1 do not work for me:

; http://www.autohotkey.com/board/topic/30624-function-httpquery-get-and-post-requests-update-036/
; httpQuery-0-3-6.ahk

httpQuery(byref p1 = "", p2 = "", p3="", p4="")
{   ; v0.3.6 (w) Oct, 26 2010 by derRaphael / zLib-Style release
   ; currently the verbs showHeader, storeHeader, and updateSize are supported in httpQueryOps
   ; in case u need a different UserAgent, Proxy, ProxyByPass, Referrer, and AcceptType just
   ; specify them as global variables - mind the varname for referrer is httpQueryReferer [sic].
   ; Also if any special dwFlags are needed such as INTERNET_FLAG_NO_AUTO_REDIRECT or cache
   ; handling this might be set using the httpQueryDwFlags variable as global
   global httpQueryOps, httpAgent, httpProxy, httpProxyByPass, httpQueryReferer, httpQueryAcceptType
       , httpQueryDwFlags
   ; Get any missing default Values
   
   ;v0.3.6
   ; check for syntax
   if ( VarSetCapacity(p1) != 0 )
      dReturn:=true,  result := "", lpszUrl := p1, POSTDATA := p2, HEADERS  := p3
   else
      result := p1, lpszUrl := p2, POSTDATA := p3, HEADERS  := p4
   
   defaultOps =
   (LTrim Join|
      httpAgent=AutoHotkeyScript|httpProxy=0|httpProxyByPass=0|INTERNET_FLAG_SECURE=0x00800000
      SECURITY_FLAG_IGNORE_UNKNOWN_CA=0x00000100|SECURITY_FLAG_IGNORE_CERT_CN_INVALID=0x00001000
      SECURITY_FLAG_IGNORE_CERT_DATE_INVALID=0x00002000|SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE=0x00000200
      INTERNET_OPEN_TYPE_PROXY=3|INTERNET_OPEN_TYPE_DIRECT=1|INTERNET_SERVICE_HTTP=3
   )
   Loop,Parse,defaultOps,|
   {
      RegExMatch(A_LoopField,"(?P<Option>[^=]+)=(?P<Default>.*)",http)
      if StrLen(%httpOption%)=0
         %httpOption% := httpDefault
   }

   ; Load Library
   hModule := DllCall("LoadLibrary", "Str", "WinINet.Dll")

   ; SetUpStructures for URL_COMPONENTS / needed for InternetCrackURL
   ; http://msdn.microsoft.com/en-us/library/aa385420(VS.85).aspx
   offset_name_length:= "4-lpszScheme-255|16-lpszHostName-1024|28-lpszUserName-1024|"
                  . "36-lpszPassword-1024|44-lpszUrlPath-1024|52-lpszExtrainfo-1024"
   VarSetCapacity(URL_COMPONENTS,60,0)
   ; Struc Size               ; Scheme Size                  ; Max Port Number
   NumPut(60,URL_COMPONENTS,0), NumPut(255,URL_COMPONENTS,12), NumPut(0xffff,URL_COMPONENTS,24)
   
   Loop,Parse,offset_name_length,|
   {
      RegExMatch(A_LoopField,"(?P<Offset>\d+)-(?P<Name>[a-zA-Z]+)-(?P<Size>\d+)",iCU_)
      VarSetCapacity(%iCU_Name%,iCU_Size,0)
      NumPut(&%iCU_Name%,URL_COMPONENTS,iCU_Offset)
      NumPut(iCU_Size,URL_COMPONENTS,iCU_Offset+4)
   }

   ; Split the given URL; extract scheme, user, pass, authotity (host), port, path, and query (extrainfo)
   ; http://msdn.microsoft.com/en-us/library/aa384376(VS.85).aspx
   DllCall("WinINet\InternetCrackUrlA","Str",lpszUrl,"uInt",StrLen(lpszUrl),"uInt",0,"uInt",&URL_COMPONENTS)

   ; Update variables to retrieve results
   Loop,Parse,offset_name_length,|
   {
      RegExMatch(A_LoopField,"-(?P<Name>[a-zA-Z]+)-",iCU_)
      VarSetCapacity(%iCU_Name%,-1)
   }
   nPort:=NumGet(URL_COMPONENTS,24,"uInt")
   
   ; Import any set dwFlags
   dwFlags := httpQueryDwFlags
   ; For some reasons using a selfsigned https certificates doesnt work
   ; such as an own webmin service - even though every security is turned off
   ; https with valid certificates works when
   if (lpszScheme = "https")
      dwFlags |= (INTERNET_FLAG_SECURE|SECURITY_FLAG_IGNORE_CERT_CN_INVALID
               |SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE)

   ; Check for Header and drop exception if unknown or invalid URL
   if (lpszScheme="unknown") {
      Result := "ERR: No Valid URL supplied."
      Return StrLen(Result)
   }

   ; Initialise httpQuery's use of the WinINet functions.
   ; http://msdn.microsoft.com/en-us/library/aa385096(VS.85).aspx
   hInternet := DllCall("WinINet\InternetOpenA"
                  ,"Str",httpAgent,"UInt"
                  ,(httpProxy != 0 ?  INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_DIRECT )
                  ,"Str",httpProxy,"Str",httpProxyBypass,"Uint",0)

   ; Open HTTP session for the given URL
   ; http://msdn.microsoft.com/en-us/library/aa384363(VS.85).aspx
   hConnect := DllCall("WinINet\InternetConnectA"
                  ,"uInt",hInternet,"Str",lpszHostname, "Int",nPort
                  ,"Str",lpszUserName, "Str",lpszPassword,"uInt",INTERNET_SERVICE_HTTP
                  ,"uInt",0,"uInt*",0)

   ; Do we POST? If so, check for header handling and set default
   if (Strlen(POSTDATA)>0) {
      HTTPVerb:="POST"
      if StrLen(Headers)=0
         Headers:="Content-Type: application/x-www-form-urlencoded"
   } else ; otherwise mode must be GET - no header defaults needed
      HTTPVerb:="GET"   

   ; Form the request with proper HTTP protocol version and create the request handle
   ; http://msdn.microsoft.com/en-us/library/aa384233(VS.85).aspx
   hRequest := DllCall("WinINet\HttpOpenRequestA"
                  ,"uInt",hConnect,"Str",HTTPVerb,"Str",lpszUrlPath . lpszExtrainfo
                  ,"Str",ProVer := "HTTP/1.1", "Str",httpQueryReferer,"Str",httpQueryAcceptTypes
                  ,"uInt",dwFlags,"uInt",Context:=0 )

   ; Send the specified request to the server
   ; http://msdn.microsoft.com/en-us/library/aa384247(VS.85).aspx
   sRequest := DllCall("WinINet\HttpSendRequestA"
                  , "uInt",hRequest,"Str",Headers, "uInt",Strlen(Headers)
                  , "Str",POSTData,"uInt",Strlen(POSTData))

   VarSetCapacity(header, 2048, 0)  ; max 2K header data for httpResponseHeader
   VarSetCapacity(header_len, 4, 0)
   
   ; Check for returned server response-header (works only _after_ request been sent)
   ; http://msdn.microsoft.com/en-us/library/aa384238.aspx
   Loop, 5
     if ((headerRequest:=DllCall("WinINet\HttpQueryInfoA","uint",hRequest
      ,"uint",21,"uint",&header,"uint",&header_len,"uint",0))=1)
      break

   If (headerRequest=1) {
      VarSetCapacity(res,headerLength:=NumGet(header_len),32)
      DllCall("RtlMoveMemory","uInt",&res,"uInt",&header,"uInt",headerLength)
      Loop,% headerLength
         if (*(&res-1+a_index)=0) ; Change binary zero to linefeed
            NumPut(Asc("`n"),res,a_index-1,"uChar")
      VarSetCapacity(res,-1)
   } else
      res := "timeout"

   ; Get 1st Line of Full Response
   Loop,Parse,res,`n,`r
   {
      RetValue := A_LoopField
      break
   }
   
   ; No Connection established - drop exception
   If (RetValue="timeout") {
      html := "Error: timeout"
      return -1
   }
   ; Strip protocol version from return value
   RetValue := RegExReplace(RetValue,"HTTP/1\.[01]\s+")
   
    ; List taken from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
   HttpRetCodes := "100=Continue|101=Switching Protocols|102=Processing (WebDAV) (RFC 2518)|"
              . "200=OK|201=Created|202=Accepted|203=Non-Authoritative Information|204=No"
              . " Content|205=Reset Content|206=Partial Content|207=Multi-Status (WebDAV)"
              . "|300=Multiple Choices|301=Moved Permanently|302=Found|303=See Other|304="
              . "Not Modified|305=Use Proxy|306=Switch Proxy|307=Temporary Redirect|400=B"
              . "ad Request|401=Unauthorized|402=Payment Required|403=Forbidden|404=Not F"
              . "ound|405=Method Not Allowed|406=Not Acceptable|407=Proxy Authentication "
              . "Required|408=Request Timeout|409=Conflict|410=Gone|411=Length Required|4"
              . "12=Precondition Failed|413=Request Entity Too Large|414=Request-URI Too "
              . "Long|415=Unsupported Media Type|416=Requested Range Not Satisfiable|417="
              . "Expectation Failed|418=I'm a teapot (RFC 2324)|422=Unprocessable Entity "
              . "(WebDAV) (RFC 4918)|423=Locked (WebDAV) (RFC 4918)|424=Failed Dependency"
              . " (WebDAV) (RFC 4918)|425=Unordered Collection (RFC 3648)|426=Upgrade Req"
              . "uired (RFC 2817)|449=Retry With|500=Internal Server Error|501=Not Implem"
              . "ented|502=Bad Gateway|503=Service Unavailable|504=Gateway Timeout|505=HT"
              . "TP Version Not Supported|506=Variant Also Negotiates (RFC 2295)|507=Insu"
              . "fficient Storage (WebDAV) (RFC 4918)|509=Bandwidth Limit Exceeded|510=No"
              . "t Extended (RFC 2774)"
   
   ; Gather numeric response value
   RetValue := SubStr(RetValue,1,3)
   
   ; Parse through return codes and set according informations
   Loop,Parse,HttpRetCodes,|
   {
      HttpReturnCode := SubStr(A_LoopField,1,3)    ; Numeric return value see above
      HttpReturnMsg  := SubStr(A_LoopField,5)      ; link for additional information
      if (RetValue=HttpReturnCode) {
         RetMsg := HttpReturnMsg
         break
      }
   }

   ; Global HttpQueryOps handling
   if strlen(HTTPQueryOps)>0 {
      ; Show full Header response (usefull for debugging)
      if (instr(HTTPQueryOps,"showHeader"))
         MsgBox % res
      ; Save the full Header response in a global Variable
      if (instr(HTTPQueryOps,"storeHeader"))
         global HttpQueryHeader := res
      ; Check for size updates to export to a global Var
      if (instr(HTTPQueryOps,"updateSize")) {
         Loop,Parse,res,`n
            If RegExMatch(A_LoopField,"Content-Length:\s+?(?P<Size>\d+)",full) {
               global HttpQueryFullSize := fullSize
               break
            }
         if (fullSize+0=0)
            HttpQueryFullSize := "size unavailable"
      }
   }

   ; Check for valid codes and drop exception if suspicious
   if !(InStr("100 200 201 202 302",RetValue)) {
      Result := RetValue " " RetMsg
      return StrLen(Result)
   }

   VarSetCapacity(BytesRead,4,0)
   fsize := 0
   Loop            ; the receiver loop - rewritten in the need to enable
   {               ; support for larger file downloads
      bc := A_Index
      VarSetCapacity(buffer%bc%,1024,0) ; setup new chunk for this receive round
      ReadFile := DllCall("wininet\InternetReadFile"
                  ,"uInt",hRequest,"uInt",&buffer%bc%,"uInt",1024,"uInt",&BytesRead)
      ReadBytes := NumGet(BytesRead)    ; how many bytes were received?
      If ((ReadFile!=0)&&(!ReadBytes))  ; we have had no error yet and received no more bytes
         break                         ; we must be done! so lets break the receiver loop
      Else {
         fsize += ReadBytes            ; sum up all chunk sizes for correct return size
         sizeArray .= ReadBytes "|"
      }
      if (instr(HTTPQueryOps,"updateSize"))
         Global HttpQueryCurrentSize := fsize
   }
   sizeArray := SubStr(sizeArray,1,-1)   ; trim last PipeChar
   
   VarSetCapacity( ( dReturn == true ) ? result : p1 ,fSize+1,0)      ; reconstruct the result from above generated chunkblocks
   Dest := ( dReturn == true ) ? &result : &p1                 ; to a our ByRef result variable
   Loop,Parse,SizeArray,|
      DllCall("RtlMoveMemory","uInt",Dest,"uInt",&buffer%A_Index%,"uInt",A_LoopField)
      , Dest += A_LoopField
      
   DllCall("WinINet\InternetCloseHandle", "uInt", hRequest)   ; close all opened
   DllCall("WinINet\InternetCloseHandle", "uInt", hInternet)
   DllCall("WinINet\InternetCloseHandle", "uInt", hConnect)
   DllCall("FreeLibrary", "UInt", hModule)                    ; unload the library
   
   if ( dReturn == true ) {
      VarSetCapacity( result, -1 )
      ErrorLevel := fSize
      return Result
   } else 
      return fSize                      ; return the size - strings need update via VarSetCapacity(res,-1)
}


C4hk
  • Members
  • 1 posts
  • Last active: Jul 03 2013 02:09 PM
  • Joined: 03 Jul 2013

 

does httpQuery-0-3-6.ahk work with AHK 1.1.9.2? the provided examples on page 1 do not work for me:

; http://www.autohotkey.com/board/topic/30624-function-httpquery-get-and-post-requests-update-036/
; httpQuery-0-3-6.ahk
.......

 

I have the same question, I tried all the examples I found on the forum and on web and nothing works.

 

Does it support the latest version of AHK ?