Jump to content
Sign in to follow this  
Surya

Convert Curl code to winhttp request

Recommended Posts

Hi everyone its been loooong since I posted here :D:lol:

I have been trying to convert this curl executable parameters into autoit using the winhttp com object;

curl -F data_file=@my_audio_file.mp3 -F model=en-US "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4jdsgjhgghstOGU5YS00OWFhLWghdgjshgdhbshj017###"

any ideas guys:D:)

 

PS: I am excited to post here after a looong time:lol:


No matter whatever the challenge maybe control on the outcome its on you its always have been.

MY UDF: Transpond UDF (Sent vriables to Programs) , Utter UDF (Speech Recognition)

Share this post


Link to post
Share on other sites
On 7/2/2018 at 11:20 AM, Surya said:

I have been trying to convert this curl executable parameters into autoit using the winhttp com object

Where is your attempt so that we can see where you are having a problem and give you some advice or guidance?

 

Edited by TheXman
Removed part about bumping post.

Share this post


Link to post
Share on other sites

hi @TheXman I am very  poor in winhttp handling this is were I have reached ,I don't know wether it is right or not

Local $sServerURL = "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4ZjQtOGU5YS00OWFhLWI3YzUtOWZkMDYwZWI3Zjg0"
Local $boundary = "--------Boundary"

Local $Postdata = "--" & $boundary & @CRLF & _
"Content-Disposition: form-data; model=en-US; data_file=" & '"' & filename($filepath) & '"' & @CRLF & _
"Content-Type: data_file" & @CRLF & @CRLF & _
Binary(FileRead($filepath)) & @CRLF & _
"--" & $boundary & "--" & @CRLF



Local $oHTTP = ObjCreate('winhttp.winhttprequest.5.1')
$oHTTP.Open("POST", $sServerURL, False)
$oHTTP.SetRequestHeader("Content-Type", "multipart/form-data; " & "boundary=" & $boundary)
$oHTTP.Send("model=en-US; data_file=" &Binary(FileRead($filepath)));$Postdata)
$hotlink = $oHTTP.ResponseText

 


No matter whatever the challenge maybe control on the outcome its on you its always have been.

MY UDF: Transpond UDF (Sent vriables to Programs) , Utter UDF (Speech Recognition)

Share this post


Link to post
Share on other sites

Here is a good example of one way to do a POST that uploads a file:

 

It uses winhttp.au3.  You can find a link the latest version of winhttp.au3 using the link below.  The zip file includes documentation that explains the winhttp.au3 functions and has several examples.

 

Assuming that you are calling the Speechmatic API correctly, this should get you closer to your goal.  If you run into an obstacles implementing the API using the example above, post back and we'll see if we can help you get past it.

 

Share this post


Link to post
Share on other sites

Hello Using WinHttp UDF you could do this:

#include "WinHTTP.au3"
Global Const $sFileToUpload = "C:\Users\User\Desktop\WinHttp\test.mp3" ;<- Set correct file location here
Global Const $sAddress = "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4jdsgjhgghstOGU5YS00OWFhLWghdgjshgdhbshj017###" ;<- Set correct host here

Local $sForm = _
        '<form action="' & $sAddress & '" method="post" enctype="multipart/form-data">' & _
        '    <input type="file" name="data_file" />' & _
        '    <input type="submit" name="model" value="en-US">' & _
        '</form>'

; Initialize and get session handle
$hOpen = _WinHttpOpen()

$hForm = $sForm

; Fill form on this page
$sRead = _WinHttpSimpleFormFill($hForm, $hOpen, Default, "name:data_file", $sFileToUpload)

; Close connection handle
_WinHttpCloseHandle($hForm)
; Close session handle
_WinHttpCloseHandle($hOpen)

; See what's returned (in default browser or whatever)
If $sRead Then
    ConsoleWrite($sRead & @CRLF)
EndIf

Saludos

Edited by Danyfirex

Share this post


Link to post
Share on other sites

voila everyone this is where I am I am unable to using winhttp it shows this

{
  "code": 400, 
  "error": "Missing data_file"
}
test.wav

 

this is the code

$filepath = FileOpenDialog("Select",@ScriptDir,"All (*.*)")
$filepah = FileOpen($filepath,16)
$output = AnonFilesUpload($filepath)

ConsoleWrite(filename($filepath) & @CRLF)
ConsoleWrite($output & @CRLF)

Func AnonFilesUpload($filepath)

 $sServerURL = "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4ZjQtOGU5YS00OWFhLWI3YzUtOMDYwZWI4Zjg0"
 $boundary = "------------WinHttpBoundaryLine_96747.69683"
;"--" &$boundary  &@CRLF & _
 ; "Content-Disposition: form-data; name=" &'"model"; ' &' value="en-US"' &@CRLF & _
   ;"Content-Type: submit" &@CRLF & _
 $Postdata = "--" & $boundary & @CRLF & _
   "Content-Disposition: form-data; name=" &'"' &"data_file" &'"' &"; filename=" &'"' &filename($filepath) &'"' &@CRLF & _
   "Content-Type: audio/x-wav" & @CRLF & @CRLF & _
   BinaryToString(FileRead($filepah)) & @CRLF &@CRLF & _
   "--" & $boundary  &@CRLF & _
   'Content-Disposition: form-data; name="model"' &@CRLF &@CRLF & _
   'en-US' &@CRLF & _
   "--" & $boundary & "--" &@CRLF
MsgBox(Default,Default,$Postdata)

 $oHTTP = ObjCreate('winhttp.winhttprequest.5.1')
 $oHTTP.Open("POST", $sServerURL, False)
 $oHTTP.SetRequestHeader("Content-Type", "multipart/form-data; " & "boundary=" & $boundary)
 $oHTTP.SetRequestHeader("Accept","application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5")
 $oHTTP.SetRequestHeader("Accept","utf-8;q=0.7")
 $oHTTP.Send($Postdata)
 $oHTTP.WaitForResponse()
 $hotlink = $oHTTP.ResponseText
 ConsoleWrite($hotlink)
 $hotlink = StringRegExpReplace(StringMid($hotlink, StringInStr($hotlink, "https")), '[/"}]', "")
   Return $hotlink
EndFunc

Func filename($filepath)
 Local $file = StringSplit($filepath, "\")
     Return $file[(UBound($file) - 1)]
EndFunc

I took the code from here 

and tried to modify it but it wont work,Can anyone please help me where I am wrong


No matter whatever the challenge maybe control on the outcome its on you its always have been.

MY UDF: Transpond UDF (Sent vriables to Programs) , Utter UDF (Speech Recognition)

Share this post


Link to post
Share on other sites

 I made it till here what am I missing again

$filepath = FileOpenDialog("Select",@ScriptDir,"All (*.*)")
$filepah = FileOpen($filepath)
$output = AnonFilesUpload($filepath)

ConsoleWrite(filename($filepath) & @CRLF)
ConsoleWrite($output & @CRLF)

Func AnonFilesUpload($filepath)

 $sServerURL = "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4ZjQtOGU5YS00OWFhUtOWZkMDYwZWI4Zjg0"
 $boundary = "------------WinHttpBoundaryLine_96747.69683"
;"--" &$boundary  &@CRLF & _
 ; "Content-Disposition: form-data; name=" &'"model"; ' &' value="en-US"' &@CRLF & _
   ;"Content-Type: submit" &@CRLF & _
 $Postdata = '--' & $boundary & @CRLF & _
   'Content-Disposition: form-data; name="model"' &@CRLF &@CRLF & _
   'en-US' &@CRLF & _
   '--' & $boundary &@CRLF & _
   'Content-Disposition: form-data; name="data_file"; filename=' &'"' &filename($filepath) &'"' &@CRLF & _
   'Content-Type: audio/x-wav' & @CRLF & @CRLF & _
    FileRead($filepah)   & @CRLF & _
   '--' & $boundary & '--'
   MsgBox(Default,Default,$Postdata)

 $oHTTP = ObjCreate('winhttp.winhttprequest.5.1')
 $oHTTP.Open("POST", $sServerURL, False)
 $oHTTP.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" & $boundary)
 $oHTTP.SetRequestHeader("Accept","application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5")
 $oHTTP.SetRequestHeader("Accept","utf-8;q=0.7")
$oHTTP.SetRequestHeader('Content-Length',StringLen($Postdata))
 $oHTTP.Send($Postdata)
 $oHTTP.WaitForResponse()
 $hotlink = $oHTTP.ResponseText
 ConsoleWrite($hotlink)
 $hotlink = StringRegExpReplace(StringMid($hotlink, StringInStr($hotlink, "https")), '[/"}]', "")
   Return $hotlink
EndFunc

Func filename($filepath)
 Local $file = StringSplit($filepath, "\")
     Return $file[(UBound($file) - 1)]
EndFunc

can someone help me..

while exexuting this i get this

--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop
{
  "code": 403, 
  "error": "Job rejected due to invalid audio"
}
tmp.wav

+>08:33:04 AutoIt3.exe ended.rc:0
+>08:33:04 AutoIt3Wrapper Finished.
>Exit code: 0    Time: 21.53

 


No matter whatever the challenge maybe control on the outcome its on you its always have been.

MY UDF: Transpond UDF (Sent vriables to Programs) , Utter UDF (Speech Recognition)

Share this post


Link to post
Share on other sites

Is there somewherw where i can learn this, anyone here hello,i tired googling and couldnt find anything all i could find was documentation of winhttp

Edited by Surya

No matter whatever the challenge maybe control on the outcome its on you its always have been.

MY UDF: Transpond UDF (Sent vriables to Programs) , Utter UDF (Speech Recognition)

Share this post


Link to post
Share on other sites

Does this work?

 

$filepath=@ScriptDir & "\test.mp3"
$sServerURL = "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4ZjQtOGU5YS00OWFhUtOWZkMDYwZWI4Zjg0"
$boundary = "------WinHttpBoundaryLine_96747.69683"
;"--" &$boundary  &@CRLF & _
; "Content-Disposition: form-data; name=" &'"model"; ' &' value="en-US"' &@CRLF & _
;"Content-Type: submit" &@CRLF & _
$Postdata = $boundary & @CRLF & _
        'Content-Disposition: form-data; name="data_file"; filename="' & filename($filepath) & '"' & @CRLF & _
        'Content-Type: audio/mpeg' & @CRLF & @CRLF & _
        FileRead($filepath) & @CRLF & _
        $boundary  & @CRLF & _
        'Content-Disposition: form-data; name="model"' & @CRLF & @CRLF & _
        'en-US' & @CRLF & _
        $boundary & "--" & @CRLF



;~ ConsoleWrite($Postdata & @CRLF)
;~ Exit

$oHTTP = ObjCreate('winhttp.winhttprequest.5.1')
$oHTTP.Open("POST", $sServerURL, False)
$oHTTP.SetRequestHeader("Content-Type", 'multipart/form-data; boundary=----WinHttpBoundaryLine_51560.17967')
$oHTTP.SetRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5")
$oHTTP.SetRequestHeader("Accept-Charset", "utf-8;q=0.7")
$oHTTP.SetRequestHeader('Content-Length', StringLen($Postdata))
$oHTTP.Send($Postdata)
$oHTTP.WaitForResponse()
$hotlink = $oHTTP.ResponseText
ConsoleWrite($hotlink)

Func filename($filepath)
 Local $file = StringSplit($filepath, "\")
     Return $file[(UBound($file) - 1)]
EndFunc

Saludos

Share this post


Link to post
Share on other sites

@Danyfirex it didn't work:(:'(:'(:'(

but the winhttp udf thing worked well,why doesn't the code work are we making any mistake or is it that my winhttp versions are not correct

I copy pasted ur code

screenshots attatched

Screenshot (16).png

Edited by Surya

No matter whatever the challenge maybe control on the outcome its on you its always have been.

MY UDF: Transpond UDF (Sent vriables to Programs) , Utter UDF (Speech Recognition)

Share this post


Link to post
Share on other sites

Hello. Here you have.

$filepath=@ScriptDir & "\zero.wav"
$sServerURL = "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4ZjQtOGU5YS00OWFhLWI3YzUtOWZkMDYwZWI4Zjg0"
$boundary = "------WinHttpBoundaryLine_96747.69683"
$Postdata = $boundary & @CRLF & _
        'Content-Disposition: form-data; name="data_file"; filename="' & filename($filepath) & '"' & @CRLF & _
        'Content-Type: application/octet-stream' & @CRLF & @CRLF & _
        BinaryToString(FileRead($filepath)) & @CRLF & _
        $boundary  & @CRLF & _
        'Content-Disposition: form-data; name="model"' & @CRLF & @CRLF & _
        'en-US' & @CRLF & _
        $boundary & "--" & @CRLF


$oHTTP = ObjCreate('winhttp.winhttprequest.5.1')
$oHTTP.Open("POST", $sServerURL, False)
$oHTTP.SetRequestHeader("User-Agent", 'Mozilla/5.0 (Windows NT 10.0; WOW64) WinHttp/1.6.3.9 (WinHTTP/5.1) like Gecko')
$oHTTP.SetRequestHeader("Content-Type", 'multipart/form-data; boundary=----WinHttpBoundaryLine_96747.69683')
$oHTTP.SetRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5")
$oHTTP.SetRequestHeader("Accept-Charset", "utf-8;q=0.7")
$oHTTP.SetRequestHeader('Content-Length', StringLen($Postdata))
$oHTTP.Send(Binary($Postdata))
$oHTTP.WaitForResponse()
$hotlink = $oHTTP.ResponseText
ConsoleWrite($hotlink)

Func filename($filepath)
 Local $file = StringSplit($filepath, "\")
     Return $file[(UBound($file) - 1)]
EndFunc

Saludos

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 Colduction
      Hi AutoIt Members and Programmers, i have a problem with Telegram UDF that does not work on some of my servers, Telegram is not restricted in these machines, here is console output in Windows 7 (Server):
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" /UserParams +>20:20:40 Starting AutoIt3Wrapper (19.1127.1402.0} from:SciTE.exe (4.2.0.0) Keyboard:00000429 OS:WIN_7/Service Pack 1 CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3 +>20:20:40 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Test file for Telegram UDF (https://github.com/xLinkOut/telegram-udf-autoit). This file need a valid ChatID of a Telegram user who has already sent at least a message to the bot, and a valid token given by @BotFather. Insert this data in the source code. "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\src\Telegram.au3" (1098) : ==> The requested action with this object has failed.: $oHTTP.Send() $oHTTP^ ERROR ->20:20:41 AutoIt3.exe ended.rc:1 +>20:20:41 AutoIt3Wrapper Finished. >Exit code: 1 Time: 1.56 It's really annoying problem in WinHTTP
    • 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 Roy_
      Ciao,
      This example reproduces the problem I encounter when sending a post request to an echo server.
      Instead of being sent as text utf8, the data is transmitted base64 encoded.
      Example:
      - json String: '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}'
      - server response: "data:application/octet-stream;base64,AAAAALgE6QNYAIAAAgAAANQCAAAAAAAAWF8AAAAAAAD0VQAAAAAAAD9APQAAAAAAAwAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAABBAAAAAAABRUAAAAmIZwcAbRt8/LMa9UAAAAAAAAAAGFzIGlkIHRlbXB1cyBtaS4gTW9yYmkgaXBzdW0gZW5pbSwgdWx0cmljaWVzIGFjIGF1Z3VlIHNpdCBhbWV0LCB1bGxhbWNvcnBlciBmaW5pYnVzIGV4LiBWZXN0aWJ1bHVtIHZlbCBwb3N1ZXJlIG5pYmgsIG5lYyBmYXVjaWJ1cyBlcm9zLiBOYW0gbWFsZXN1YWRhIG5vbiBsYWN1cyBhIHN1c2NpcGl0LiBOdWxsYSByaG9uY3VzIHRlbXB1cyBtaSBxdWlzIHBsYWNlcmF0LiBDdXJhYml0dXIgY29tbW9kbyB0aW5jaWR1bnQganVzdG8gcXVpcyBzb2xsaWNpdHVkaW4uIn0="
       
      How can I go about transmitting data in text format utf8?
      Thanks in advance for the help.
      In the zip file:
      - CurlJsonPost.au3: this script
      - Curl.au3: UDF by Ward (thank you!)
      - data.json: json srting for command line test
       
      Note: using Curl.exe with json string saved in a file (utf8 encoded) named data.json, works perfectly
      To try with the command line tool:
      - save data.json in curl\bin directory
      - open cmd.exe and cd to curl\bin directory
      - Enter the following command:
      curl -H "Content-Type: application/json" --data @data.json https://httpbin.org/post
       
      #Include "Curl.au3" Global $_cURL_OutputBuffer Local $sJson = '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}' Local $iRetCode, $sServerResponse ConsoleWrite("=== Json post test ===" & @LF) ConsoleWrite(StringFormat("Retcode: %s - %s", $iRetCode, Curl_Easy_strerror($iRetCode)) & @LF) ConsoleWrite("Data returned from server" & @LF & @LF) $sServerResponse = JsonPost_Test($sJson, $iRetCode) ConsoleWrite($sServerResponse & @LF) Func JsonPost_Test($sJson, ByRef $iRetCode) ; Init Easy Curl Interface e set url (echo service) Local $oCurl = Curl_Easy_Init() curl_easy_setopt($oCurl, $CURLOPT_URL, "https://httpbin.org/post") ; Set content type header Local $headers = curl_slist_append(0, "Content-Type: application/json") curl_easy_setopt($oCurl, $CURLOPT_HTTPHEADER, $headers) ; Post fields & size curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDS, $sJson) curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDSIZE, StringLen($sJson)) ; Set callbac function to get server response back (see global var $_cURL_OutputBuffer) $hWriteFunc = DllCallbackRegister("WriteFunc_CallBack", "uint:cdecl", "ptr;uint;uint;ptr") curl_easy_setopt($oCurl, $CURLOPT_WRITEFUNCTION, DllCallbackGetPtr($hWriteFunc)) ; Ignore ssl certificates check curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYPEER, 0) curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYHOST, 0) ; Execute the post request $iRetCode = curl_easy_perform($oCurl) ; Set return trasfer & clear output buffer global var Local $sReturnTransfer = $_cURL_OutputBuffer $_cURL_OutputBuffer = "" Return SetError(0, 0, $sReturnTransfer) EndFunc Func WriteFunc_CallBack($ptr,$nSize,$nMemb,$pStream) Local $vData = DllStructCreate ("byte[" & $nSize*$nMemb & "]",$ptr) $_cURL_OutputBuffer &= BinaryToString(DllStructGetData($vData,1)) Return $nSize*$nMemb EndFunc  
      curlJsonPost.zip
    • By Rex
      Some time ago I needed a way to uploade images to imgur, from one of my programs, and took a look at there API.
      Don't know if anyone can/would use it, but here is my code
       
      #AutoIt3Wrapper_Au3Check_Parameters=-q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7 ; #INDEX# ======================================================================================================================= ; Title .........: IMGUR Curl udf ; AutoIt Version : 1.0 ; Description ...: Uploads files to imgur using curl, and returns imgur url, deletion key, imgsize ect. in an array ; Author(s) .....: Rex ; =============================================================================================================================== #include-once #include <curl.au3> ; By Ward #include <JSON.au3> ; by Ward ; #FUNCTION# ==================================================================================================================== ; Name...........: _Imgur ; Description ...: Allows the user to uploade images to Imgur, or delete an already uploaded image using the images DeleteHash ; Syntax.........: _Imgur($AuthKey, True/False, $vData) ; Parameters ....: $AuthKey - API key from Imgur ; $bImg_Up - If true an image uploade is expected, if False a DeleteHas is expected ; $vData - The image to uploade, or the DeleteHash that was returned from Imgur at Image uploade ; Return values .: Success - An Array containing: ID, Datetime, type, animated, width, height, size, deletehash and url ; Failur - Sets @Error to 1 if no AuthKey is provided ; Failur - Sets @Error to 2 if $bImg_Up = True but no Image data is provided ; Failur - Sets @Error to 3 if $bImg_Up = True but $vData isn't Binary ; Failur - Sets @Error to 4 if $bImg_Up = False but no DeleteHash is provided ; Failur - Sets @Error to 5 if the API returns 400 -> Bad Request ; Failur - Sets @Error to 6 if the API returns 403 -> Permission Denied ; Failur - Sets @Error to 7 if the API returns 413 -> Data to large ; Failur - Sets @Error to 8 if the API returns 415 -> Unsupported data ; Failur - Sets @Error to 9 if Curl returns no Curl ; Failur - Sets @Error to 10 and returns Curl error msg if Curl fails ; Failur - Sets @Error to 11 If StringRegExp failed on the header (no array) ; Author ........: Rex ; Modified.......: ; Remarks .......: Needs Curl, Json And BinaryCall by Ward - Base64Encode By Ward and _EPOCH_Decrypt by Trancexx ; Is includede in the UDF is self ; Related .......: ; Link ..........: ; Example .......: $dFile = FileOpenDialog('Open', @ScriptDir, 'Image Files (*.jpg;*.jpeg;*.png;*.bmp;*.gif)', 1) ; Browse image ; $hData = FileOpen($dFile, 16) ; Open as binary ; $dData = FileRead($hData) ; Read the data ; FileClose($hData) ; Close the FileHandle ; $aData = _Imgur('APIKEY', True, $dData) ; Uploade the Image ; ; $aDelete = _Imgur('APIKEY', False, 'DELETEHASH') ; ; =============================================================================================================================== Func _Imgur($sAuthKey, $bImg_Up = True, $vData = '') ; Performe some error checking Select Case $sAuthKey = '' ; If no authkey is provided Return SetError(1, 0, -1) ; We set error to 1 Case $vData = '' And $bImg_Up = True ; If no image data is sendt Return SetError(2, 0, -1) ; We sent error to 2 Case $vData <> '' And $bImg_Up = True And IsBinary($vData) = 0 ; If $vData isn't binary Return SetError(3, 0, -1) ; We sent error to 3 Case $vData = '' And $bImg_Up = False ; If no deleta hash was send Return SetError(4, 0, -1) ; We sent error to 4 EndSelect Local $aResult[9] ; Return array Local $ProgressCallback = DllCallbackGetPtr(DllCallbackRegister("ShowProgress", "int:cdecl", "ptr;uint64;uint64;uint64;uint64")) Local $Curl = Curl_Easy_Init() If Not $Curl Then Return SetError(9, 0, -1) Local $sHtml = $Curl Local $sHeader = $Curl + 1 ; any number as identify Local $sList = Curl_Slist_Append(0, "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:34.0) Gecko/20100101 Firefox/34.0") $sList = Curl_Slist_Append($sList, 'Referer: http://imgur.com/') $sList = Curl_Slist_Append($sList, 'Type: Base64') $sList = Curl_Slist_Append($sList, "Authorization: client-ID " & $sAuthKey) Curl_Easy_Setopt($Curl, $CURLOPT_HTTPHEADER, $sList) ; If $bImg_Up is true we uploads the image If $bImg_Up = True Then $dImage = _Base64Encode($vData) ; Convert the image to Base64 Curl_Easy_Setopt($Curl, $CURLOPT_URL, "https://api.imgur.com/3/upload/") ; If we wants to uploade an image Curl_Easy_Setopt($Curl, $CURLOPT_POST, 1) Curl_Easy_Setopt($Curl, $CURLOPT_COPYPOSTFIELDS, $dImage) Else ; If no img we expect a delete Curl_Easy_Setopt($Curl, $CURLOPT_URL, "https://api.imgur.com/3/image/" & $vData) ; If we wants to delete an image Curl_Easy_Setopt($Curl, $CURLOPT_CUSTOMREQUEST, 'DELETE') ; When we deletes an image EndIf ; Get header Curl_Easy_Setopt($Curl, $CURLOPT_HEADERFUNCTION, Curl_DataWriteCallback()) Curl_Easy_Setopt($Curl, $CURLOPT_HEADERDATA, $sHeader) Curl_Easy_Setopt($Curl, $CURLOPT_FOLLOWLOCATION, 1) ; Checks use this to see the respons from server, and get img url/delete hash ect. Curl_Easy_Setopt($Curl, $CURLOPT_WRITEFUNCTION, Curl_DataWriteCallback()) Curl_Easy_Setopt($Curl, $CURLOPT_WRITEDATA, $sHtml) Curl_Easy_Setopt($Curl, $CURLOPT_TIMEOUT, 30) Curl_Easy_Setopt($Curl, $CURLOPT_SSL_VERIFYPEER, 0) Curl_Easy_Setopt($Curl, $CURLOPT_NOPROGRESS, 0) Curl_Easy_Setopt($Curl, $CURLOPT_XFERINFOFUNCTION, $ProgressCallback) Local $Code = Curl_Easy_Perform($Curl) If $Code <> $CURLE_OK Then Return SetError(10, 0, Curl_Easy_StrError($Code)) EndIf ;ConsoleWrite(@CRLF & 'HEADER: ' & BinaryToString(Curl_Data_Get($sHeader)) & @CRLF) ;ConsoleWrite(@CRLF & 'HTML RAW: ' & BinaryToString(Curl_Data_Get($sHtml)) & @CRLF) ; Check what the header returns $aHeader = StringRegExp(BinaryToString(Curl_Data_Get($sHeader)), 'HTTP/1.1 (400|403|413|415|200)', 1) If IsArray($aHeader) Then Select Case $aHeader[0] = 400 ; If 403 then Permission Denied Return SetError(5, 0, -1) Case $aHeader[0] = 403 ; If 403 then Permission Denied Return SetError(6, 0, -1) Case $aHeader[0] = 413 ; If 413 then the data is to large Return SetError(7, 0, -1) Case $aHeader[0] = 415 ; If 415 then the data is unsupported Return SetError(8, 0, -1) Case $aHeader[0] = 200 ; If 200 uploade/delete was a sucess ; Decode the json returned from imgur Local $sJson = Json_Decode(BinaryToString(Curl_Data_Get($sHtml))) ; If deleting an image we only needs to return Sucess - IMGUR returns Sucess If $bImg_Up = False Then ReDim $aResult[1] ; Slim down the array $aResult[0] = 'Success' Return $aResult EndIf ; If an image was uploaded then we need to return some data to the user $aResult[0] = Json_Get($sJson, '["data"]["id"]') ; Imgur image id ; Date time the image was uploaded, it's returned in unix timestamp, so we converts it to regular time stamp $aResult[1] = _EPOCH_Decrypt(Json_Get($sJson, '["data"]["datetime"]')) ; Type of uploaded image $aResult[2] = Json_Get($sJson, '["data"]["type"]') ; Was the image animated $aResult[3] = Json_Get($sJson, '["data"]["animated"]') ; Width of the image $aResult[4] = Json_Get($sJson, '["data"]["width"]') ; Height of the image $aResult[5] = Json_Get($sJson, '["data"]["height"]') ; Size of the image $aResult[6] = Json_Get($sJson, '["data"]["size"]') ; Delete hash of the image $aResult[7] = Json_Get($sJson, '["data"]["deletehash"]') ; Image link $aResult[8] = Json_Get($sJson, '["data"]["link"]') Curl_Easy_Cleanup($Curl) Curl_Data_Cleanup($Curl) Curl_Slist_Free_All($sList) Return $aResult EndSelect Else ; If the Regexp failed Return SetError(11, 1, -1) EndIf EndFunc ;==>_Imgur Func ShowProgress($Ptr, $dltotal, $dlnow, $ultotal, $ulnow) ProgressSet(Int($ulnow / $ultotal * 100), '% Sendt = ' & Int($ulnow / $ultotal * 100)) Return 0 EndFunc ;==>ShowProgress ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name ..........: _EPOCH_Decrypt ; Description ...: Converts Epoch Time to human time ; Syntax ........: _EPOCH_Decrypt(TIMESTAMP) ; Return values .: Convertede timestamp ; Author ........: Trancexx ; Modified ......: ; Remarks .......: ; =============================================================================================================================== Func _EPOCH_Decrypt($iEpochTime) ; By trancexx forum thread: https://www.autoitscript.com/forum/topic/83667-epoch-time/ Local $iDayToAdd = Int($iEpochTime / 86400) Local $iTimeVal = Mod($iEpochTime, 86400) If $iTimeVal < 0 Then $iDayToAdd -= 1 $iTimeVal += 86400 EndIf Local $i_wFactor = Int((573371.75 + $iDayToAdd) / 36524.25) Local $i_xFactor = Int($i_wFactor / 4) Local $i_bFactor = 2442113 + $iDayToAdd + $i_wFactor - $i_xFactor Local $i_cFactor = Int(($i_bFactor - 122.1) / 365.25) Local $i_dFactor = Int(365.25 * $i_cFactor) Local $i_eFactor = Int(($i_bFactor - $i_dFactor) / 30.6001) Local $aDatePart[3] $aDatePart[2] = $i_bFactor - $i_dFactor - Int(30.6001 * $i_eFactor) $aDatePart[1] = $i_eFactor - 1 - 12 * ($i_eFactor - 2 > 11) $aDatePart[0] = $i_cFactor - 4716 + ($aDatePart[1] < 3) Local $aTimePart[3] $aTimePart[0] = Int($iTimeVal / 3600) $iTimeVal = Mod($iTimeVal, 3600) $aTimePart[1] = Int($iTimeVal / 60) $aTimePart[2] = Mod($iTimeVal, 60) Return StringFormat("%.2d/%.2d/%.2d %.2d:%.2d:%.2d", $aDatePart[0], $aDatePart[1], $aDatePart[2], $aTimePart[0], $aTimePart[1], $aTimePart[2]) EndFunc ;==>_EPOCH_Decrypt ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name ..........: _Base64Encode ; Description ...: Encodes data into Base64 ; Syntax ........: _Base64Encode(Data, Linebreak) ; Return values .: Base64 Encodede string ; Author ........: Ward ; Modified ......: ; Remarks .......: ; =============================================================================================================================== Func _Base64Encode($Data, $LineBreak = 76) ; By Ward Local $Opcode = '0x5589E5FF7514535657E8410000004142434445464748494A4B4C4D4E4F505152535455565758595A6162636465666768696A6B6C6D6E6F707172737' $Opcode &= '475767778797A303132333435363738392B2F005A8B5D088B7D108B4D0CE98F0000000FB633C1EE0201D68A06880731C083F901760C0FB6430125F0000000C1' $Opcode &= 'E8040FB63383E603C1E60409C601D68A0688470183F90176210FB6430225C0000000C1E8060FB6730183E60FC1E60209C601D68A06884702EB04C647023D83F' $Opcode &= '90276100FB6730283E63F01D68A06884703EB04C647033D8D5B038D7F0483E903836DFC04750C8B45148945FC66B80D0A66AB85C90F8F69FFFFFFC607005F5E' $Opcode &= '5BC9C21000' Local $CodeBuffer = DllStructCreate("byte[" & BinaryLen($Opcode) & "]") DllStructSetData($CodeBuffer, 1, $Opcode) $Data = Binary($Data) Local $Input = DllStructCreate("byte[" & BinaryLen($Data) & "]") DllStructSetData($Input, 1, $Data) $LineBreak = Floor($LineBreak / 4) * 4 Local $OputputSize = Ceiling(BinaryLen($Data) * 4 / 3) $OputputSize = $OputputSize + Ceiling($OputputSize / $LineBreak) * 2 + 4 Local $Ouput = DllStructCreate("char[" & $OputputSize & "]") DllCall("user32.dll", "none", "CallWindowProc", "ptr", DllStructGetPtr($CodeBuffer), _ "ptr", DllStructGetPtr($Input), _ "int", BinaryLen($Data), _ "ptr", DllStructGetPtr($Ouput), _ "uint", $LineBreak) Return DllStructGetData($Ouput, 1) EndFunc ;==>_Base64Encode I have added Wards curl, json and BinaryCall to the att. zip file.
       
      Cheers
      /Rex
      Includes.zip
    • By Ascer
      Hello
      Opertation Sys: Win7 x64
      Problem: Connecting to webs using TLS 1.1 +
      Description: WinHttp.WinHttpRequest.5.1 using TLS 1.0 by default, i need higher version to connect into some webs.
      Dim $oHttp = ObjCreate("WinHTTP.WinHTTPRequest.5.1") $oHttp.open ("GET", "https://howsmyssl.com/a/check", False) $oHttp.Option(9) = 128 ; 128 - TLS 1.0, 512 - TLS 1.1, 2048 - TLS 1.2, 2056 - TLS 1.1 & TLS 1.2 $oHttp.Send ConsoleWrite($oHttp.responseText & @CRLF) ; at end of the respond you can check your TLS version. Mine is: {"tls_version":"TLS 1.0","rating":"Bad"} Error: $oHttp.Option works only with parameter 128 (TLS 1.0) other values make error {Bad parameter}
      Additional: I've done this tutorial about enabling TLS in registry: <link>
      Thanks for support.
      Ascer
×
×
  • Create New...