Jump to content

WinHTTP functions


trancexx
 Share

Recommended Posts

It could be something like this:

#include <WinHttp.au3>

$url = "https://slack.com/api/files.upload"
$token = "abc-123-456-abc123"
$args = "#random"
$file = "c:\Users\Public\catloloz.jpg"

; example curl command -- curl -F file=@c:\Users\Public\catloloz.jpg -F channels=#random -F token=abc-123-456-abc123 https://slack.com/api/files.upload


$sForm = _
        '<form action="' & $url & '" method="post" enctype="multipart/form-data">' & _
        ' <input type="file" name="file"/>' & _ ;
        ' <input name="channels" />' & _
        ' <input name="token" />' & _
        '</form>'

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

$hConnect = $sForm ; will pass form as string so this is for coding correctness because $hConnect goes in byref

; Fill form
$sHTML = _WinHttpSimpleFormFill($hConnect, $hOpen, _
        Default, _
        "name:file", $file, _
        "name:channels", $args, _
        "name:token", $token)

If @error Then
    MsgBox(4096, "Error", "Error number = " & @error)
Else
    ConsoleWrite("!" & $sHTML & @CRLF)
EndIf

; Close handles
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)

 

♡♡♡

.

eMyvnE

Link to comment
Share on other sites

  • 4 months later...
1 hour ago, samibb said:

WHEN I RUN EXAMPLE AT HOME WAS WORKING. BUT ON NETWORK NOT WORKING.

IS THERE ANY SETTING BE4 USING WINHTTP?

@trancexx : Background information :)

To understand what this question is about at all, see https://www.autoitscript.com/forum/topic/203849-winhttp-invalid-server-response/?do=findComment&comment=1471590

Musashi-C64.png

"In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."

Link to comment
Share on other sites

  • 1 month later...

Hello,

i'm trying to use the WinHttp functions to read and write to a relay board. i have no problem for reading data with GET Method. But i can't find how to write something using the PUT method as asked in the documentation.

According to the restfulAPI documentation of the board ( https://www.moxa.com/getmedia/6b024adb-5276-429d-9837-1235ee4ac836/moxa-iologik-e1200-series-manual-v15.9.pdf )

jtxAtoI.png

sxvUK3R.png

So i haveto use the PUT method, is that working with WinHttp ?

this is actualy how i read something :

#include "json.au3"
        #include "WinHttp.au3"
        $hOpen = _WinHttpOpen() ; Initialize and get session handle
        $hConnect = _WinHttpConnect($hOpen, "192.168.8.250") ; Get connection handle

        Local $hRequest = _WinHttpOpenRequest($hConnect, Default, "/api/slot/0/io/relay")
        _WinHttpAddRequestHeaders($hRequest, "Content-Type: application/json")
        _WinHttpAddRequestHeaders($hRequest, "Accept: vdn.dac.v1")
        _WinHttpSendRequest($hRequest)
        _WinHttpReceiveResponse($hRequest)
        $data = _WinHttpReadData($hRequest)

        Local $sHeader = _WinHttpQueryHeaders($hRequest)
        ;MsgBox(0, "Header", $sHeader)

        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        _WinHttpCloseHandle($hOpen)

        $object = json_decode($data)
        $relayCurrentCount = json_get($object, '[io][relay][4][relayCurrentCount]')

        msgbox ("","Result", "relayCurrentCount = " & $relayCurrentCount )

 

And below my PHP code, using cURL to write something with a PUT method :

<?php

$ch = curl_init("http://192.168.8.250/api/slot/0/io/relay/0/relayStatus"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: vdn.dac.v1'
));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, '$sPost = '{"slot":0,"io":{"relay":{"0":{"relayStatus":1}}}}');
$result = curl_exec($ch);
curl_close($ch);

echo $result;

?>

So my question is, how can i do the same with WinHTTP ??

Thank you for helping.

Edited by cetipabo
add pdf link
Link to comment
Share on other sites

Finaly i found something that works, but i don't know if this is the correct way to add the custom headers ??

$hOpen = _WinHttpOpen()
        $hConnect = _WinHttpConnect($hOpen, '192.168.8.250')

        $sPost = '{"slot":0,"io":{"relay":{"0":{"relayStatus":1}}}}'

        $sResult = _WinHttpSimpleRequest($hConnect, "PUT", '/api/slot/0/io/relay/0/relayStatus', '', $sPost, "Accept: vdn.dac.v1" & @CRLF & "Content-Type: application/json")
        _WinHttpCloseHandle($hConnect)
        _WinHttpCloseHandle($hOpen)

 

Link to comment
Share on other sites

  • 10 months later...

Try to transfer the script (workable) to WinHttp UDF type always got fail, does anyone could help me

Original Script

$arb_Http = ObjCreate("winhttp.winhttprequest.5.1")
$arb_Http.Open("post", "http://test123.com", False)
$arb_Http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
$arb_Http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36")

$arb_Http.Send("name=test_name&status=test_status")

$arb_Result = $arb_Http.ResponseText

MsgBox(0, "", $arb_Result)

WinHttp

$arb_Http = _WinHttpOpen("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36")

$arb_Connect = _WinHttpConnect($HRBS_AR_Http, "http://test123.com")
$arb_Request = _WinHttpOpenRequest($HRBS_AR_Connect, "post")

_WinHttpSendRequest($arb_Request, "Content-Type: application/x-www-form-urlencoded", "name=test_name&status=test_status")
_WinHttpReceiveResponse($arb_Request)
   
$arb_Request = _WinHttpReadData($arb_Request)

_WinHttpCloseHandle($arb_Request)
_WinHttpCloseHandle($arb_Connect)
_WinHttpCloseHandle($arb_Http)

MsgBox(0, "", $arb_Result)

 

Edited by jimmy123j
Link to comment
Share on other sites

  • 1 month later...

Hallo,

I like to do  Http Request with winHttp.au3, but for me is no function. I tried it for 3 Days i dont know what i doing wrong.

Local $sTarget = "/sites/siteXX/_api/Web/Lists/getbytitle('Helper')/items("&$sWebsiteItemId&")" & _
                  "?$select=CurrentVersion,InfoText,LinkText"

    Local $sSiteUrl = "https://team.xxxxx.de"

    local $sHeader = _
            'Content-Type:application/json' & @CRLF & _
            'Accept:application/json;odata=verbose' & @CRLF & _
            'X-RequestDigest:"' &  $sToken

    #cs ; in Javascript (JQuery) i will write for the request:

        var requestUrl =siteUrl + path;
         return $.ajax({
                url: requestUrl,
                type: "GET",
                cache: true,
                async: false,
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                },
        });
    #ce

    Local $hOpen = _WinHttpOpen(Default,$WINHTTP_ACCESS_TYPE_DEFAULT_PROXY) ; use the default proy setting in win System
    local $hConnect = _WinHttpConnect($hOpen,$sSiteUrl)
    local $hRequest =_WinHttpSimpleSSLRequest($hConnect,"GET", $sTarget, Default, Default, $sHeader, Default, Default, Default, Default, 1)

#cs _WinHttpAddRequestHeaders($hRequest,"Content-Type:application/json")
    _WinHttpAddRequestHeaders($hRequest,"Accept:application/json;odata=verbose")
    _WinHttpAddRequestHeaders($hRequest,"X-RequestDigest:" &  $sToken )
#ce
    ConsoleWrite("Response: "& $hRequest & @CRLF)
;Send the request
_WinHttpSendRequest($hRequest)

ConsoleWrite:  Response: 401 UNAUTHORIZED

We use am Proxy normally ? I dont now what happend. Can everybody help me? 

Thanks, 

Link to comment
Share on other sites

  • 2 weeks later...

I find a workaround of my problem. I used another ddl ("MSXML2.XMLHTTP.6.0")  and do my own request , step by step. like:

; Simple Code without my Errorhandler 
    ; (By POST, sometime i get a com error from the ddl, but the Request was OK)
      
    $HttpRequest = ObjCreate("MSXML2.XMLHTTP.6.0")


    $HttpRequest.open("POST",$sRequestURI,False)
    $HttpRequest.setRequestHeader("Content-Type","application/json;odata=verbose")
    $HttpRequest.setRequestHeader("Accept","application/json")
    $HttpRequest.setRequestHeader("X-RequestDigest",$sToken)
    $HttpRequest.setRequestHeader("X-HTTP-Method","MERGE")
    $HttpRequest.setRequestHeader("If-Match","*")

    $HttpRequest.send($sJsonProdData)
    $HttpStatus = $HttpRequest.status

 

Link to comment
Share on other sites

  • 2 months later...

Hello everyone,

I'm trying to set some radio boxes in a web form but no way to make it works.

This is how the form looks like:

<FORM ACTION="InternalForm.HTM" METHOD=POST>
            <TR><TD><I><B> SELECT THE OPTIONS:  </B></I></TD></TR>
            <TR><TD> Model 800      </TD></TR>  <INPUT type="radio" name="model_equip" value="0"    checked>
            <TR><TD> Model 1300     </TD></TR>  <INPUT type="radio" name="model_equip" value="1"    >
            <HR>
            <TR><TD><I><B> Accessory one:   </B></I></TD></TR>
            <TR><TD>ENABLE      </TD></TR>  <INPUT type="radio" name="accessory_one" value="1"  >
            <TR><TD>DISABLE     </TD></TR>  <INPUT type="radio" name="accessory_one" value="0"  checked>
            <HR>
            <TR><TD><I><B> Accessory two:   </B></I></TD></TR>
            <TR><TD>ENABLE      </TD></TR>  <INPUT type="radio" name="accessory_two" value="1"  >
            <TR><TD>DISABLE     </TD></TR>  <INPUT type="radio" name="accessory_two" value="0"  checked>
            <BR>(BLUE CASE)
            <HR>
            <TR><TD><I><B> Accessory three: </B></I></TD></TR>
            <TR><TD>ENABLE      </TD></TR>  <INPUT type="radio" name="accessory_three" value="1"    >
            <TR><TD>DISABLE     </TD></TR>  <INPUT type="radio" name="accessory_three" value="0"    checked>
            <BR>(GREEN CASE)
            <HR>
            <INPUT type="hidden" name="PAGE_SELECT" value="21" />
            <INPUT TYPE="submit" VALUE="EXECUTE">
        </FORM>

 

I copied many parts from the examples here https://github.com/dragana-r/autoit-winhttp/tree/master/WinHttp_Examples but I didn`t find any example for radio selections. This is what I tried so far:

Local $hOpen, $hConnect
   Local $sRead, $hFileHTM
   Local $hRequest

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

   ; Get connection handle
   $hConnect = _WinHttpConnect($hOpen, "192.168.1.1")

   ConsoleWrite(@CRLF & "************************************************************" & @CRLF)
   ; Request
   $hRequest = _WinHttpSimpleSendRequest($hConnect)     ; Gets the main page - OK
   ConsoleWrite($sRead)                                 ; Shows the mains page - OK.
   
   
   ConsoleWrite(@CRLF & "************************************************************" & @CRLF)
   ; Request
   $hRequest = _WinHttpSimpleSendRequest($hConnect, Default, "defaultform.htm")     ; Go to form - OK

   ; Simple-read...
   $sRead = _WinHttpSimpleReadData($hRequest)           ; Gets the page content - OK
   ConsoleWrite($sRead)                                 ; Shows the page content - OK
   
   
   ConsoleWrite(@CRLF & "************************************************************" & @CRLF)
   ; Fill form on this page
   ; Here I can not select the radios and I have no idea how they are identified...
   $sRead = _WinHttpSimpleFormFill($hConnect, "defaultform.htm", _
               "index:0", _
               "type:radio name:model_equip & value='0'", "true", _ ;"//input[@name='module_animal_type'][@value='1']", "checked", _
               "name:model_equip & value:0", "unchecked", _         ; Do not work!
               "name:accessory_one value:1", "checked", _           ; Do not work!
               "name:accessory_two, value:0", "true", _             ; Do not work!
               "name:accessory_three & value:0", "true"             ; Do not work!
               )
   ConsoleWrite($sRead)                 ; Show the returned page, in this case it should returns the same form with the new selections.

 

Thanks in advance!

 

Link to comment
Share on other sites

  • 1 month later...
  • 4 weeks later...

Currently in the WinHTTP UDF when making a call to a site that requests a client certificate but does not require it fails when  WINHTTP_OPTION_CLIENT_CERT_CONTEXT is set to Null pointer. In the WinHTTP reference from Microsoft the WINHTTP_NO_CLIENT_CERT_CONTEXT macro is Null pointer and can be returned to let the requesting application know you don't have one.

This is fixed in this pull request if anyone needs this functionality. 

https://github.com/dragana-r/autoit-winhttp/pull/16

 

This issue apparent in this post and the solution presented is just to do the same DLL call that the WinHTTP UDF does under the hood but to provide the correct format for the null pointer.

Link to comment
Share on other sites

  • 2 months later...
On 7/7/2022 at 2:08 PM, Danp2 said:

@ChuckeroDid you try like this?

$sRead = _WinHttpSimpleFormFill($hConnect, "defaultform.htm", _
               "index:0", _
               "name:accessory_three", "1"
               )
ConsoleWrite($sRead)

 

Thanks Danp2, but it's not so simple.

The web page have two controls with the same name:

<TR><TD>ENABLE      </TD></TR>  <INPUT type="radio" name="accessory_three" value="1"    >
<TR><TD>DISABLE     </TD></TR>  <INPUT type="radio" name="accessory_three" value="0"    checked>

The difference is the property "value", this is why I'm trying to identify it by a second property:

$sRead = _WinHttpSimpleFormFill($hConnect, "defaultform.htm", _
               "index:0", _
               "name:accessory_three value:1", "1"
               )
ConsoleWrite($sRead)

I didn't figure out a way to identify the controls using more than one property. Identifying by only one property makes the first one be selected.

 

Edited by Chuckero
Link to comment
Share on other sites

  • 1 year later...

Is there any other way to get Content-length other than using regex?

 

#include <WinHttp.au3>

Local $hOpen = _WinHttpOpen()
IF @error Then
        Msgbox(0,"Error","_WinHttpOpen")
        Exit
EndIF

Local $hConnect = _WinHttpConnect($hOpen, "http://www.autoitscript.com")
IF @error Then
        Msgbox(0,"Error","_WinHttpConnect")
        Exit
EndIF

Local $hRequest = _WinHttpOpenRequest($hConnect, "GET", "/autoit3/files/beta/update.dat")
IF @error Then
        Msgbox(0,"Error","_WinHttpOpenRequest")
        Exit
EndIF

_WinHttpSendRequest($hRequest)
IF @error Then
        Msgbox(0,"Error","_WinHttpSendRequest")
        Exit
EndIF

_WinHttpReceiveResponse($hRequest)
IF @error Then
        Msgbox(0,"Error","_WinHttpReceiveResponse")
        Exit
EndIF

IF _WinHttpQueryDataAvailable($hRequest) Then
        $headers = _WinHttpQueryHeaders($hRequest)
        
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        _WinHttpCloseHandle($hOpen)
        
        $FileLength = StringRegExpReplace($headers, '(?s).*Content-Length:\h*(\d+).*', "$1") 
        Msgbox(0,"Length", $FileLength)
Else
        Msgbox(0,"No Have Data","No Have Data!")
EndIF

 

Edited by r2du-soft
Link to comment
Share on other sites

I guess

Local $iConLenght = 0, $aHeader = StringSplit($sHeader, @CRLF)
For $n = 1 To $aHeader[0]
    If StringInStr($aHeader[$n], "Content-Length: ") = 1 Then $iConLenght = Int(StringReplace($sString, "Content-Length: ", ""))
Next

 but why are you asking that ?

Edited by argumentum

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

  • 1 month later...
On 11/7/2019 at 6:19 PM, JoeBar said:

Hi, thank you for your nice UDF, i have a problem.


Here is the help in the SDK page of my app :

I tried with curl,  of course it's working.

I'm trying to do the same request in Autoit and my current "don't working" request is :

Global $hRequestSSL = _WinHttpSimpleSSLRequest($hConnect, "POST", $sDomain, Default, "grant_type=client_credentials", Default, Default, Default, $sClientID, $sClientSct)

I don't know which parameter to change to put grant_type=client_credentials (it's the only body of the request) or if i need to switch function for another one.

Thanks for your time !

Edit : I found how to proceed :

Global $hRequestSSL = _WinHttpSimpleSSLRequest($hConnect, "POST", $sDomain, Default, "client_id=" & $sClientID & "&" & "client_secret=" & $sClientSct & "&" & "grant_type=client_credentials")

Hi @JoeBar

Did you get Dell API to work?

Yours sincerely

Kenneth.

Link to comment
Share on other sites

  • 2 weeks later...
  • 4 weeks later...
Quote

Sample request:

curl -X PUT \
‘https://api.allegro.pl/order/checkout-forms/a8320af2-5f01-11eb-bbeb-112e13b418c5/invoices/56ae349d-8045-4bb3-adcc-7cf6fb420f61/file' \
-H ‘Accept: application/vnd.allegro.public.v1+json’ \
-H ‘Content-Type: application/pdf’ \
-H ‘Authorization: Bearer {token}’ \
-d 'data=@example-invoice.pdf’

is it possible to do it with WinHttp functions? Send PUT HTTP request with file content? I want to upload pdf invoice to my customer for order in marketplace website via API

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...