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

    • Surya
      By Surya
      Hi everyone its been loooong since I posted here 
      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
       
      PS: I am excited to post here after a looong time
    • Seminko
      By Seminko
      I'm trying to get data from http://poe.trade/ - disclaimer, although this site is about a game, my script will not in any way interact directly with the game in any way. The script is just to get data from the site.
      To explain how it works - you submit a POST request and a custom URL is returned, then you do a GET request on that URL and you get the final URL you want.
       
      First issue:
      Now, I've tried doing so by using https://apitester.com/ and the first phase works. Here's how it looks like at APITester:
      Request Headers POST /search HTTP/1.1 Host: poe.trade Accept: */* User-Agent: Rigor API Tester Content-Length: 43 Content-Type: application/x-www-form-urlencoded Request Body online=x&name=kaom%27s%20heart&league=incursion When I submit this, the response I get is this:
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting...</title> <h1>Redirecting...</h1> <p>You should be redirected automatically to target URL: <a href="http://poe.trade/search/ioritewoteteme">http://poe.trade/search/ioritewoteteme</a>. If not click the link. So I then do a GET request for 'http://poe.trade/search/ioritewoteteme', which results in this response:
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting...</title> <h1>Redirecting...</h1> <p>You should be redirected automatically to target URL: <a href="http://poe.trade/search/inamotezuakito">http://poe.trade/search/inamotezuakito</a>. If not click the link. Great, this link (http://poe.trade/search/inamotezuakito) is exactly what we want.
      However, when I try to do the same in autoit, the result is quite different:
      Global Const $HTTP_STATUS_OK = 200 $test = HttpPost("http://poe.trade/search", "/online=x&name=kaom%27s%20heart&league=incursion") ClipPut($test) MsgBox(1, "", $test) Func HttpPost($sURL, $sData = "") Local $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1") $oHTTP.Open("POST", $sURL, False) If (@error) Then Return SetError(1, 0, 0) $oHTTP.SetRequestHeader("Host", "poe.trade") $oHTTP.SetRequestHeader("User-Agent", "Rigor API Tester") $oHTTP.SetRequestHeader("Accept", "*/*") $oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded") $oHTTP.Send($sData) If (@error) Then Return SetError(2, 0, 0) If ($oHTTP.Status <> $HTTP_STATUS_OK) Then Return SetError(3, 0, 0) Return SetError(0, 0, $oHTTP.ResponseText) EndFunc The code above returns: ' 謟 '
      Any ideas as to what I am doing incorrectly?
       
      Second issue:
      Once I get the final link using APITester and do a GET on that i get a bunch of hieroglyphs. A friend of mine advised that the data is GZiped, which is a pain in the butt to be honest. However, apparently curl can uncompres that.
      How would I go about it?
       
      Thanks
    • 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  
       
×