Jump to content
sivaramanm

WinHTTP Send with Complex Send Parameters

Recommended Posts

sivaramanm

Have this following input parameter(Complex list of inputs) that need to be SEND as part of HTTP POST Request. 

Have been searching forums to find an AutoIT equivalent to enapsulate the following data, but unsuccessful.

Below given Working Code is failing with 400-Bad Request for obvious reason of incomplete input - unable to send ip_list and other array type parameters

Questions:

1. How to encapsulate the below given data for $oHttp.Send()

2. How to enapsulate special data types like

 null - aligned_device_tempate parameter

White sapced values - () and

empty array? - hostname or device_groups

 

Input Parameter in JSON format to be converted & sent in AutoIT compatible

{
      "name": "SnmpSIM",
      "description": "EM7 device created by BDD test case",
      "credentials":"{{feature.credential.body.result_set[*].URI}}", 
      "organization": "/api/organization/0",
      "aligned_device_template": null,
      "aligned_collector": "{{feature.appliance_id[0].id[0]}}{{feature.appliance_id[0].id[1]}}",
      "discover_non_snmp": "1",
      "scan_ports": [
        "21",
        "22",
        "23",
        "25",
        "80"
      ],
      "ip_lists": [
        {
        "start_ip": "{{feature.json.ip}}",
        "end_ip": "{{feature.json.ip}}"
        }
      ],
      "dhcp_enabled": "0",
      "duplicate_protection": "1",
      "model_device": "1",
      "log_all": "1",
      "scan_all_ips": null,
      "port_scan_timeout": null,
      "initial_scan_level": null,
      "scan_throttle": null,
      "interface_inventory_timeout": "600000",
      "max_interface_inventory_count": "10000",
      "bypass_interface_inventory": "0",
      "hostnames": [],
      "device_groups": []
    }

 

Working Code

; The data to be sent
$sPD = 'name=SnmpSIM&description=EM7 device created by BDD test case&credentials=37&organization=/api/organization/0&aligned_device_template=null&aligned_collector=1&discover_non_snmp=1&dhcp_enabled=0&duplicate_protection=1&model_device=1&log_all=1&scan_all_ips= null&port_scan_timeout= null&initial_scan_level= null&scan_throttle= null&interface_inventory_timeout=600000&max_interface_inventory_count=10000&bypass_interface_inventory=0&hostnames=&device_groups=&scan_ports=21'

; Creating the object
$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("POST", "http://10.2.4.18/api/discovery_session", False)
$oHTTP.SetCredentials("username","password",0)

$oHTTP.SetRequestHeader("Content-Type", "application/em7-resource-uri")

; Performing the Request
$oHTTP.Send($sPD)

; Download the body response if any, and get the server status response code.
$oReceived = $oHTTP.ResponseText
$oStatusCode = $oHTTP.Status

If $oStatusCode <> 200 then
 MsgBox(4096, "Response code", $oStatusCode)
EndIf

; Saves the body response regardless of the Response code
 $file = FileOpen("Received.html", 2) ; The value of 2 overwrites the file if it already exists
 FileWrite($file, $oReceived)
 FileClose($file)

 


 SAMPLE VBA CODE for Reference

 Dim Items As New Collection
 Dim Item As Dictionary
 Dim Id As Long

 For Id = 1 To 2
     Set Item = New Dictionary
     Item("iditem") = Id
     Item("amount") = 1
     Items.Add Item
 Next Id
 Request.AddBodyParameter "id", 5633
 Request.AddBodyParameter "items", Items

$oDictionary = ObjCreate("Scripting.Dictionary")
$oDictionary.ADD("start_ip", "10.20.7.31")
$oDictionary.ADD("end_ip", "10.20.7.33")

 

Edited by sivaramanm

Share this post


Link to post
Share on other sites
sivaramanm

Need some help sending the following JSON content. I have looked at the JSON UDFs available here but couldn't understand how to use them for my use.

    {
      "name": "SnmpSIM",
      "description": "EM7 device created by BDD test case",
      "credentials":"{{feature.credential.body.result_set[*].URI}}", 
      "organization": "/api/organization/0",
      "aligned_device_template": null,
      "aligned_collector": "{{feature.appliance_id[0].id[0]}}{{feature.appliance_id[0].id[1]}}",
      "discover_non_snmp": "1",
      "scan_ports": [
        "21",
        "22",
        "23",
        "25",
        "80"
      ],
      "ip_lists": [
        {
        "start_ip": "{{feature.json.ip}}",
        "end_ip": "{{feature.json.ip}}"
        }
      ],
      "dhcp_enabled": "0",
      "duplicate_protection": "1",
      "model_device": "1",
      "log_all": "1",
      "scan_all_ips": null,
      "port_scan_timeout": null,
      "initial_scan_level": null,
      "scan_throttle": null,
      "interface_inventory_timeout": "600000",
      "max_interface_inventory_count": "10000",
      "bypass_interface_inventory": "0",
      "hostnames": [],
      "device_groups": []
    }

 

Auto-IT Script:

$JSONString = ""
$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("GET", "http://10.2.4.18/api/credential/snmp?limit=100", False)
$oHTTP.SetCredentials("em7admin","em7admin",0)

$oHTTP.SetRequestHeader("Content-Type", "application/em7-resource-uri")

$oHTTP.Send($JSONString) ; **Need helpt to encapsulate the JSON String.**
$oReceived = $oHTTP.ResponseText
$oStatusCode = $oHTTP.Status

If $oStatusCode == 200 then
 $file = FileOpen("Received.html", 2) ; The value of 2 overwrites the file if it already exists
 FileWrite($file, $oReceived)
 FileClose($file)
EndIf

 

Share this post


Link to post
Share on other sites
sivaramanm

@Danp2 Thanks for your response. I have looked at WinHTTP UDF. my issue is i am not sure how to send the JSON content either as a variable or as a binary data file.
for instance cURL utulity has the following option to send the JSON data as a binary file.

I am looking for either to send the JSON data in serialised format like key1=value1&key2=value2 format (which i tried but not working as given below) or sending as binary data file.

curl -v -H 'X-em7-beautify-response:1' -u 'username:password' "https://192.168.10.205/api/ticket/279/note" -H 'content-type:application/json' -- data-binary @new_note.json



Below one fails with 400-Bad Request Error.(Most likely due to invalid JSON format)

$sPD = '"{""name"":""SnmpSIM"",""description"":""EM7devicecreatedbyBDDtestcase"",""credentials"":""/api/credential/snmp/38"",""organization"":""/api/organization/0"",""aligned_device_template"":null,""aligned_collector"":""3"",""discover_non_snmp"":""1"",""scan_ports"":[""21"",""22"",""23"",""25"",""80""],""ip_lists"":[{""start_ip"":""{{feature.json.ip}}"",""end_ip"":""{{feature.json.ip}}""}],""dhcp_enabled"":""0"",""duplicate_protection"":""1"",""model_device"":""1"",""log_all"":""1"",""scan_all_ips"":null,""port_scan_timeout"":null,""initial_scan_level"":null,""scan_throttle"":null,""interface_inventory_timeout"":""600000"",""max_interface_inventory_count"":""10000"",""bypass_interface_inventory"":""0"",""hostnames"":[],""device_groups"":[]}"'

$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("POST", "http://10.2.4.31/api/discovery_session_active", False)
$oHTTP.SetCredentials("username","password",0)

$oHTTP.SetRequestHeader("Content-Type", "application/json")

$oHTTP.Send($sPD)
$oReceived = $oHTTP.ResponseText
$oStatusCode = $oHTTP.Status

 MsgBox(1,1,$oStatusCode)
Exit


If $oStatusCode == 200 then
 $file = FileOpen("Received.html", 2) ; The value of 2 overwrites the file if it already exists
 FileWrite($file, $oReceived)
 FileClose($file)
Else
     MsgBox(1,1,$oStatusCode)
EndIf

 

Edited by sivaramanm

Share this post


Link to post
Share on other sites
Jos

@sivaramanm, no need to created a second thread on the same topic, so please stick to one topic going forward.

Merged.

Jos

  • Like 1

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
AutoBert

try this

$oHTTP.Send(StringToBinary($sPD,SB_UTF8))

Maybe you have to change SB_UTF8 to a other value:

[optional] Changes how the string is stored as binary:
    $SB_ANSI (1) = string data is ANSI (default)
    $SB_UTF16LE (2) = string data is UTF16 Little Endian
    $SB_UTF16BE (3) = string data is UTF16 Big Endian
    $SB_UTF8 (4) = string data is UTF8

 

Share this post


Link to post
Share on other sites
orbs

@sivaramanm,

you may try the following:

1) what's the deal with the double-double-quotes in your JSON string? replace each pair of double-quotes characters with a single double-quotes character.

2) i'm not at all certain you need the enclosing double-quotes around your entire JSON string. try to remove them.

3) you may need to escape the double-quotes inside the JSON string. something like this:

$sPD = '"{\"name\":\"SnmpSIM\",\"description\":\"EM7devicecreatedbyBDDtestcase\",\"credentials\":\"/api/credential/snmp/38\",\"organization\":\"/api/organization/0\",\"aligned_device_template\":null,\"aligned_collector\":\"3\",\"discover_non_snmp\":\"1\",\"scan_ports\":[\"21\",\"22\",\"23\",\"25\",\"80\"],\"ip_lists\":[{\"start_ip\":\"{{feature.json.ip}}\",\"end_ip\":\"{{feature.json.ip}}\"}],\"dhcp_enabled\":\"0\",\"duplicate_protection\":\"1\",\"model_device\":\"1\",\"log_all\":\"1\",\"scan_all_ips\":null,\"port_scan_timeout\":null,\"initial_scan_level\":null,\"scan_throttle\":null,\"interface_inventory_timeout\":\"600000\",\"max_interface_inventory_count\":\"10000\",\"bypass_interface_inventory\":\"0\",\"hostnames\":[],\"device_groups\":[]}"'

this is after replacing each pair of double-double-quotes ("") with a backslash and a double=quotes (\"), but the enclosing double-quotes pair is maintained.

i know for a fact that escaping the double-quotes inside the JSON string is required when passing it to an external utility, e.g. cURL. not sure if this is needed in a direct call.

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

  • Similar Content

    • Ascer
      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
    • islandspapand
      By islandspapand
      Hi All
      i am currently trying to add a function to my project that can send SMS, i have gone with Twilio for the sms service that use a REST API.
      I have never worked with an API before, and could use some help.
      I can get my function working with using cURL.exe and copy past command from the website with the following code. And thats great unfortunately i am have issue with character like æøå when sending a SMS appears like a box or ?. this does not happen if i do it from the website so it looks like a Unicode issue in curl.exe.
      I have done some searching on the forum and understand that i should be able to implement this curl command with the WinHTTP UDF from @trancexx so i don't need a third part exe and it might fix my charater issue.
      Unfortunately i really don't understand how i am to change curl commands to the WinHTTP and i was hoping some good maybe give me an example i could learn from.
      Thanks in advanced
      i have removed the AuthToken number from the script.
      _SendSMS("00000000","SomeOne","SMS body info") Func _SendSMS($SendTo,$SendFrom,$Msgtxt) $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc" $AuthToken = "Auth Token number" $Data = '"https://api.twilio.com/2010-04-01/Accounts/'&$AccountSID&'/Messages.json"'& _ '-X POST \ --data-urlencode "To=+45'&$SendTo&'" \ --data-urlencode "From='&$SendFrom&'" \ --data-urlencode "Body='&$Msgtxt&'" \ -u '&$AccountSID&':'&$AuthToken&'' ShellExecute(@ScriptDir&"\curl.exe","-k "&$Data) ;~ curl 'https://api.twilio.com/2010-04-01/Accounts/ACbb765b3180d5938229eff8b8f63ed1bc/Messages.json' -X POST \ ;~ --data-urlencode 'To=+4500000000' \ ;~ --data-urlencode 'From=Reception' \ ;~ --data-urlencode 'Body=Test Body' \ ;~ -u ACbb765b3180d5938229eff8b8f63ed1bc:[AuthToken] EndFunc  
       
    • Ward
      By Ward
      Introduction
      JSON (Javascript Object Notation) is a popular data-interchange format and supported by a lot of script languages. On AutoIt, there is already a >JSON UDF written by Gabriel Boehme. It is good but too slow, and not supports unicode and control characters very well. So I write a new one (and of course, fast one as usual).

      I use a machine code version of JSON parser called "jsmn". jsmn not only supports standard JSON, but also accepts some non-strict JSON string. See below for example.
       
      Important Update!!
      I rename the library from jsmn.au3 to json.au3. All function names are changed, too.
       
      Decoding Function
      Json_Decode($Json) $Json can be a standard or non-standard JSON string. For example, it accepts:
      { server: example.com port: 80 message: "this looks like a config file" } The most JSON data type will be decoded into corresponding AutoIt variable, including 1D array, string, number, true, false, and null. JSON object will be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). AutoIt build-in functions like IsArray, IsBool, etc. can be used to check the returned data type. But for Object and Null, Json_IsObject() and Json_IsNull() should be used.

      If the input JSON string is invalid, @Error will be set to $JSMN_ERROR_INVAL. And if the input JSON string is not finish (maybe read from stream?), @Error will be set to $JSMN_ERROR_PART.

      Encoding Function
      Json_Encode($Data, $Option = 0, $Indent = "\t", $ArraySep = ",\r\n", $ObjectSep = ",\r\n", $ColonSep = ": ") $Data can be a string, number, bool, keyword(default or null), 1D arrry, or "Scripting.Dictionary" COM object. Ptr will be converted to number, Binary will be converted to string in UTF8 encoding. Other unsupported types like 2D array, dllstruct or object will be encoded into null.

      $Option is bitmask consisting following constant:
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f) $JSON_UNESCAPED_UNICODE ; Encode multibyte Unicode characters literally $JSON_UNESCAPED_SLASHES ; Don't escape / $JSON_HEX_TAG ; All < and > are converted to \u003C and \u003E $JSON_HEX_AMP ; All &amp;amp;amp;amp;s are converted to \u0026 $JSON_HEX_APOS ; All ' are converted to \u0027 $JSON_HEX_QUOT ; All " are converted to \u0022 $JSON_PRETTY_PRINT ; Use whitespace in returned data to format it $JSON_STRICT_PRINT ; Make sure returned JSON string is RFC4627 compliant $JSON_UNQUOTED_STRING ; Output unquoted string if possible (conflicting with $JSMN_STRICT_PRINT) Most encoding option have the same means like PHP's json_enocde() function. When $JSON_PRETTY_PRINT is set, output format can be change by other 4 parameters ($Indent, $ArraySep, $ObjectSep, and $ColonSep). Because these 4 output format parameters will be checked inside Jsmn_Encode() function, returned string will be always accepted by Jsmn_Decode(). $JSON_UNQUOTED_STRING can be used to output unquoted string that also accetped by Jsmn_Decode().

      $JSON_STRICT_PRINT is used to check output format setting and avoid non-standard JSON output. So this option is conflicting with $JSON_UNQUOTED_STRING.

      Get and Put Functions
      Json_Put(ByRef $Var, $Notation, $Data, $CheckExists = False) Json_Get(ByRef $Var, $Notation) These functions helps user to access object or array more easily. Both dot notation and square bracket notation can be supported. Json_Put() by default will create non-exists objects and arrays. For example:
      Local $Obj Json_Put($Obj, ".foo", "foo") Json_Put($Obj, ".bar[0]", "bar") Json_Put($Obj, ".test[1].foo.bar[2].foo.bar", "Test") Local $Test = Json_Get($Obj, '["test"][1]["foo"]["bar"][2]["foo"]["bar"]') ; "Test" Object Help Functions
      Json_ObjCreate() Json_ObjPut(ByRef $Object, $Key, $Value) Json_ObjGet(ByRef $Object, $Key) Json_ObjDelete(ByRef $Object, $Key) Json_ObjExists(ByRef $Object, $Key) Json_ObjGetCount(ByRef $Object) Json_ObjGetKeys(ByRef $Object) Json_ObjClear(ByRef $Object) These functions are just warps of "Scripting.Dictionary" COM object. You can use these functions if you are not already familiar with it.
       
      == Update 2013/05/19 ==
       
      * Add Jsmn_Encode() option "$JSMN_UNESCAPED_ASCII". Now the default output of Json_Encode() is exactly the same as PHP's json_encode() function (for example, chr(1) will be encoded into u0001).
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f)  
      == Update 2015/01/08 ==
      * Rename the library from jsmn.au3 to json.au3. All function names are changed, too.
      * Add Json_Put() and Json_Get()
      * Add Null support
      * Using BinaryCall.au3 to loading the machine code.
       
      == Update 2018/01/13=   Jos
      * Add JsonDump() to list all Json Keys and their values to easily figure out what they are.

      JSMN.zip
      JSMN.zip
      Json.zip
      Json(2018.01.13).zip
    • jesus40
      By jesus40
      Hello friends, i have a working curl command that show informations about my account on binance.com, but_it dont work with autoit code without curl.exe.
      I want to do it without curl, because the whole process much Slower_ with StdoutRead (I want get the response in variable.)
      My Curl command in Autoit:
      This 2 are works, but_ i would like to do it without curl.exe
      $apikey="XYZ" sCommand = @ScriptDir & '\curl.exe -k -H "X-MBX-APIKEY: ' & $apikey & '" -X GET "https://api.binance.com/api/v3/account?' & $request the same in .bat  file
      curl.exe -k -H "X-MBX-APIKEY: XYZ" -X GET "https://api.binance.com/api/v3/account?timestamp=1514917812000&signature=85bdee77e53cd521e1d5229fbfb459d53799c42b3fa4596d73f1520fad5f965a" (I use curl with -k option which allows curl to make insecure connections, because there is problem with the sites certificate, (cURL error 60))
       
      I tried many variations, this is the latest... I cant get the same response.
      curl $error message (I changed ): {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}
      autoit version $error message (Response code:400): Mandatory parameter 'timestamp' was not sent, was empty/null, or malformed.
       
      $request = $query & '&signature=' & $signature $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "https://api.binance.com/api/v3/account", False) $oHTTP.SetRequestHeader("X-MBX-APIKEY", $apikey) $oHTTP.Send($request) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then MsgBox(4096, "Response code", $oStatusCode) EndIf  
      thanks
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.