Jump to content
Sign in to follow this  
Ward

Request UDF - The simplest way to make HTTP request

Recommended Posts

Like Request for node.js or Requests for python, Request UDF is a powerful and easy-to-use HTTP client for AutoIt. 

It is based on my Curl.au3 and Json.au3 (not included). 

The Features:

  • Request target can be a string (single url), an array (urls), an object (single url + options or url array + options), an object array (urls + different options), or a json string (decode to array or object automatically), etc.
  • Easy to setup post data, cookies, agent, refer, timeout, proxy, etc.
  • Easy to setup the default options before a series of requests.
  • Use BinaryToString() to decode the returned data according to content type automatically. 
  • Use curl multi interface by default. It means all requests will transfer simultaneously and won't block the GUI event.
  • Use callback function to recieve the data and information for every url before main function finished.
  • Supports https and ftp protocols.

Example:

#Include "Json.au3"
#Include "Curl.au3"
#Include "Request.au3"

RequestDefault('{refer: "http://www.autoitscript.com", agent: "AutoIt/Request", callback: "MyCallback"}')

Local $Data = Request("http://httpbin.org/get")
ConsoleWrite($Data & @LF)

Request('["http://www.google.com", "http://wikipedia.org"]')
Request('{url: "http://www.google.com", agent: "AutoIt/Request"}')
Request('{url: ["http://www.google.com", "http://wikipedia.org"], agent: "AutoIt/Request"}')
Local $Array[] = ["http://www.google.com", "http://wikipedia.org"]
Request($Array)
Request("http://httpbin.org/post", "key=Post%20can%20be%20the%20raw%20data")
Request("http://httpbin.org/post", '{key: "Post can be a json object string"}')
Request('{url: "http://httpbin.org/post", post:{key: "Post can be set as second paramemtr or \"post\" option"}}')
Local $Obj
Json_Put($Obj, ".key", "Post can be an object")
Local $Json = Request("http://httpbin.org/post", $Obj)

Func MyCallback($Obj)
    Local $Data = Json_ObjGet($Obj, "Data")
    Local $EffectiveUrl = Json_ObjGet($Obj, "EffectiveUrl")
    ConsoleWrite("Callback: " & $EffectiveUrl & " download size: " & StringLen($Data) & @LF)
EndFunc

More examples are in the archive.

Request.zip

Edited by Ward

新版 _ArrayAdd 的白痴作者,不管是誰,去死一死好了

 

Share this post


Link to post
Share on other sites

Added to the UDF list in the wiki :)


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2020-07-21 - Version 1.5.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2020-06-27 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (NEW 2020-06-27 - Version 1.3.2.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Share this post


Link to post
Share on other sites

@Ward: which is the right BinaryCall.au3?  (It's in two of the zips.)

I went with the 2015 version and got some undefined fcns.

Also, I got the error below.  Typo?

 

Error.PNG

Edited by qwert

Share this post


Link to post
Share on other sites

Shouldn't there be a space character in the last line before "Then $Callback = Execute($Callback)"


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2020-07-21 - Version 1.5.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2020-06-27 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (NEW 2020-06-27 - Version 1.3.2.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Share this post


Link to post
Share on other sites

Yes, adding a space takes care of that.  But has anyone been able to run the example?  If so, with which BinaryCall.au3?

My attempt is stopped by two missing MemoryModule functions.

 

Share this post


Link to post
Share on other sites

qwert, change this part in BinaryCall

If $HasMemoryDll Then
                Local $Module = Execute('__MemoryModule_ModuleRecord("get", Null, $DllName)')
                If $Module Then
                    Local $MemoryGetProcAddress = Execute('__MemoryModule_RuntimeLoader("MemoryGetProcAddress")')
                    If $MemoryGetProcAddress Then $Proc = DllCallAddress("ptr:cdecl", $MemoryGetProcAddress, "ptr", $Module, "str", $ProcName)[0]
                    If Not $Proc Then Return SetError(2, _BinaryCall_LastError("MemoryGetProcAddress failed on " & $ProcName), False)
                EndIf
            EndIf

 

Share this post


Link to post
Share on other sites

That took care of it.  Using the above example, I got the result shown below.

The actions are logged ... but are the downloads actually stored?

 

 

Result.thumb.PNG.1cd635b191b05c8e6c269af

 

Edited by qwert

Share this post


Link to post
Share on other sites

What, then, would be an appropriate write statement?  I guess I'm asking where is the content for a download and what format is it?

Sorry to be so persistent, but this is all brand new to me and I'm trying to get a handle on its use.

Share this post


Link to post
Share on other sites

What, then, would be an appropriate write statement?  I guess I'm asking where is the content for a download and what format is it?

Sorry to be so persistent, but this is all brand new to me and I'm trying to get a handle on its use.

​is plain text. reading the code you could do:

Func MyCallback($Obj)
    Local $Data = Json_ObjGet($Obj, "Data")
    Local $EffectiveUrl = Json_ObjGet($Obj, "EffectiveUrl")
    ConsoleWrite('--- '&$Data&' ---'&@LF) ; <--- to see the downloaded data
    ConsoleWrite("Callback: " & $EffectiveUrl & " download size: " & StringLen($Data) & @LF)
EndFunc

Unfortunately not everything we find here is for just copy, paste and shine. Read the code. After 700+ posts you should know how.

Ward, thanks for sharing, great code.

Edited by argumentum

Share this post


Link to post
Share on other sites

Thank you very much for such a great UDF. I am just trying to use it

#Include "Json.au3"
#Include "Curl.au3"
#Include "Request.au3"

Local $Backup = RequestDefault('{agent: "Autoit/Request", cookiefile: "cookie.txt", cookiejar: "cookie.txt", }')
Local $Data = Request('http://www.w3schools.com/html/html_forms.asp')
Local $Post
Json_Put($Post, ".firstname", "intro")
Json_Put($Post, ".lastname", "intro")
    Local $Obj = Request('{url: "http://www.w3schools.com/html/action_page.php", returnobj: true}', $Post)
FileWrite (@DesktopDir & "\3.txt", $Obj)

What am I doing wrong in this code? It returns nothing

Great thanx in advance!

Share this post


Link to post
Share on other sites

 I needed PUT request for my REST application, so I quickly added CUSTOM_REQUEST support.

See cURL MAN page - -X, --request <command>

 

11c11
< ;   Request($Request, $Post = Null)
---
> ;   Request($Request, $Post = Null, $CustomRequest = Null)
108c108
< Func Request($Request, $Post = Null)
---
> Func Request($Request, $Post = Null, $CustomRequest = Null)
179a180,181
>     If Not IsKeyword($CustomRequest) Then Json_ObjPut($OptList, "customrequest", $CustomRequest)
> 
311a314
>     If Json_ObjExists($Obj, "customrequest") Then Curl_Easy_Setopt($Curl, $CURLOPT_CUSTOMREQUEST, Json_ObjGet($Obj, "customrequest"))
320a324
> 

 PATCH 

Request.au3

Edited by recmund

Share this post


Link to post
Share on other sites

 I needed PUT request for my REST application, so I quickly added CUSTOM_REQUEST support.

See cURL MAN page - -X, --request <command>

 

11c11
< ;   Request($Request, $Post = Null)
---
> ;   Request($Request, $Post = Null, $CustomRequest = Null)
108c108
< Func Request($Request, $Post = Null)
---
> Func Request($Request, $Post = Null, $CustomRequest = Null)
179a180,181
>     If Not IsKeyword($CustomRequest) Then Json_ObjPut($OptList, "customrequest", $CustomRequest)
> 
311a314
>     If Json_ObjExists($Obj, "customrequest") Then Curl_Easy_Setopt($Curl, $CURLOPT_CUSTOMREQUEST, Json_ObjGet($Obj, "customrequest"))
320a324
>

 PATCH 

Request.au3

Do you have request.au3 which include cUrl.au3 and json.au3 or where i can download it :(

thanks

Share this post


Link to post
Share on other sites

Do you have request.au3 which include cUrl.au3 and json.au3 or where i can download it :(
thanks

ok, here they are, from my PC, in Curl there is a folder "changed by argumentum" and you may need the file from there if BinaryCall gives you trouble.
As soon as the files are back, I'll remove this post and attached files.

Request(2015.06.07).zip

Curl(2015.06.04).zip

Json(2015.01.08).zip

Share this post


Link to post
Share on other sites

ok, here they are, from my PC, in Curl there is a folder "changed by argumentum" and you may need the file from there if BinaryCall gives you trouble.As soon as the files are back, I'll remove this post and attached files.

Request(2015.06.07).zip

Curl(2015.06.04).zip

Json(2015.01.08).zip

I want to implement curl like that. How can i put a header to curl :(. 

 

Edited by fairylovehn127

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Jahar
      Hi,
      I am new to Autoit, Kindly guide me. I wanted to send a message with HTTP/GET to the URL https://ghsff.it/. How to do so?
    • By tarretarretarre
      About AutoIt-API-WS
      AutoIt-API-WS is a light weight web server with expressive syntax, with the sole purpose of wrapping your existing AutoIt app with little to no effort.
      With AutoIt-API-WS you can send and receive data between any application or framework, as long they can handle HTTP requests, which is an industry standard today.
      Like my other communcations UDF AutoIt-Socket-IO AutoIt-API-WS is heavily inspired from the big boys, but this time its Laravel and Ruby on Rails.
      Features Highlights
      No external or internal dependencies required RESTful mindset when designed Expressive syntax Small codebase Heavy use of Michelsofts Dictionary object Limitations
      Not complient with any RFC, so something important could be missing. Time will tell! One persons slow loris attack will kill the process forever. Example of implemetnation (With screenshots)
      This is a basic cRud operation with the RESTful mindset in use.
      #include "API.au3" #include <Array.au3> _API_MGR_SetName("My APP DB adapter") _API_MGR_SetVer("1.0 BETA") _API_MGR_SetDescription("This adapter allows you to get this n that") _API_MGR_Init(3000) _API_MGR_ROUTER_GET('/users', CB_GetUsers, 'string sortBy', 'Get all users, sortBy can be either asc or desc. asc is default') _API_MGR_ROUTER_GET('/users/{id}', CB_GetUsersById, 'int id*', 'Get user by id') While _API_MGR_ROUTER_HANDLE() WEnd Func DB_GetUsers() Local $userA = ObjCreate("Scripting.Dictionary") Local $userB = ObjCreate("Scripting.Dictionary") $userA.add('id', 1) $userA.add('name', 'TarreTarreTarre') $userA.add('age', 27) $userB.add('id', 2) $userB.add('name', @UserName) $userB.add('age', 22) Local $aRet = [$userA, $userB] Return $aRet EndFunc Func CB_GetUsers(Const $oRequest) Local $aUsers = DB_GetUsers() If $oRequest.exists('sortBy') Then Switch $oRequest.item('sortBy') Case Default Case 'asc' Case 'desc' _ArrayReverse($aUsers) EndSwitch EndIf Return $aUsers EndFunc Func CB_GetUsersById(Const $oRequest) Local Const $aUsers = DB_GetUsers() Local $foundUser = Null For $i = 0 To UBound($aUsers) -1 Local $curUser = $aUsers[$i] If $curUser.item('id') == $oRequest.item('#id') Then $foundUser = $curUser ExitLoop EndIf Next If Not IsObj($foundUser) Then Return _API_RES_NotFound(StringFormat("Could not find user with ID %d", $oRequest.item('#id'))) EndIf return $foundUser EndFunc When you visit http://localhost:3000 you are greeted with this pleasent view that will show you all your registred routes and some extra info you have provided.

      When you visit http://localhost:3000/users the UDF will return the array of objects as Json
       
      And here is an example of http://localhost:3000/users/1

       
      More examples can be found here
       
       
      Autoit-API-WS-1.0.0-beta.zip (OLD!)
      Autoit-API-WS-1.0.1-beta.zip (NEWEST 2020-06-29)
    • By nacerbaaziz
      goodmorning autoit team
      today am comming with some winhttp problems, i hope that you can help me to solve them.
      the first problem
      is when opening a request
      my forums api allow me to delete any post using the api key
      all functions work, i mean post / get
      but when i tried to use the delete verb it's gave me an html 404 error
      here is what am tried
      #include "WinHttp.au3" ; Open needed handles Global $hOpen = _WinHttpOpen() Global $hConnect = _WinHttpConnect($hOpen, "xxxxxxxx.com") ; Specify the reguest: Global $hRequest = _WinHttpOpenRequest($hConnect, "Delete", "/vb/Api/posts/10447/?hard_delete=true", default, default) _WinHttpAddRequestHeaders($hRequest, "XF-Api-Key:xxxxx") _WinHttpAddRequestHeaders($hRequest, "XF-Api-User:xxxxx") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Global $sHeader = 0, $sReturned = 0 ; If there is data available... If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_DISPOSITION) ;Or maybe: ; $sHeader = _WinHttpQueryHeaders($hRequest, BitOR($WINHTTP_QUERY_RAW_HEADERS_CRLF, $WINHTTP_QUERY_CUSTOM), "Content-Disposition") Do $sReturned &= _WinHttpReadData($hRequest) Until @error msgBox(64, "", $sReturned) endIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen)  
      and here is the error message
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access /vb/Api/posts/10447/ on this server.<br /> </p> </body></html>  
      i hope you can help me 
      thanks in advance
    • By Miliardsto
      Im making requests to REST API WORDPRESS
      is it right code ?
      $metabox = 'meta_box={"uuid":" ' & urlEncode($MY_ID) & ' "}' _httpRequest("https://MYSITE/wp-json/wp/v2/users/" & $id &"?", "POST", $metabox,$success) In postman im making request like this and its working. it should be the same in autoit
      https://MYSITE/wp-json/wp/v2/users/8?meta_box={"uuid": "2342342342"}
    • By argumentum
      I can TCP/IP in AutoIt, hence, make a HTTP deamon. Now, how can I HTTPS to use SSL !??
      Well, Apache has this "mod_proxy.so" module that can let me have SSL and what not is in Apache.
      All that is needed is to tell Apache what I wanna do by editing httpd.conf .
      # Implements a proxy/gateway for Apache. # 1. Open /Applications/XAMPP/etc/httpd.conf # 2. Enable the following Modules by removing the # at the front of the line. # - LoadModule rewrite_module modules/mod_rewrite.so # - LoadModule proxy_module modules/mod_proxy.so # - LoadModule proxy_http_module modules/mod_proxy_http.so # # 3. Copy and Paste below to the bottom of httpd.conf # <IfModule mod_proxy.c> ProxyRequests On <Proxy *> Order deny,allow Allow from all </Proxy> ProxyVia Off ProxyPreserveHost Off ProxyPass /home/ http://127.0.0.1:84/home/ ProxyPassReverse /home/ http://127.0.0.1:84/home/ SetEnv proxy-nokeepalive 1 # ..since we are not using "keep-alive", we are using "close" </IfModule> ...et voila  
      I'm using XAMPP ( https://www.apachefriends.org/download.html )
      and this is my solution to avoid coding in PHP, as I feel more comfortable coding in AutoIt.
      A "muli-thread or concurrency" can be done by forking the socket ( https://www.autoitscript.com/forum/topic/199177-fork-udf-ish/ )
      but responses are under 20 ms., so I feel fine with a single thread.
      I modified an example ( attached below ), so can try out the concept.
      PS: I am not an Apache guru. I just discovered this and it opens a world of possibilities. In my case, I'm thinking of an API to query SQLite 
      PS2: I'm not gonna make Poll but do click like if you do  
       
      201673-json-http-post-serverlistener.au3
×
×
  • Create New...