Jump to content

Recommended Posts

Posted

Hi,

I need to send a POST request.

I have this specs:

image.png.9251f42797be7ce18ab06748ff7a51ca.png

So I write this code:

$sBody = 'username=myrealusername&password=]=oN9>fh2!O'

$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("POST", "https://XXXXXXXXXXXXXXXXXXXXXXXX/api/login", False)
$oHTTP.setRequestHeader("cache-control", "no-cache")
$oHTTP.SetRequestHeader("Accept", "application/json")
$oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")

; Performing the Request
$oHTTP.Send($sBody)
$oHttp.WaitForResponse()

; Download the body response if any, and get the server status response code.
$oReceived = $oHTTP.ResponseText
$oStatusCode = $oHTTP.Status
ConsoleWrite("$oReceived: " & $oReceived & @CRLF)

but the response is:

$oReceived: {"code":400,"error":"Validation Error","message":"Field 'password' in the body is required."}

I also tried with

$sBody = 'username:myrealusername&password:]=oN9>fh2!O'

but it does not work;

$oReceived: {"code":400,"error":"Validation Error","message":"Field 'username' in the body is required."}

 

Do you have any suggestions? Thank you!

Marco

 

Posted (edited)

Your initial example, when sent to the POSTMAN Echo API, sends the form data correctly.  Are you sure you are posting the correct script and error message?  If so, then the problem is probably the format of the POST data.  It would help if you provided more information about the API.  The site doesn't have API examples? 

You could also try URL encoding your POST data before sending it.  The second $sPostData in my example has the string URL encoded.  Both ways produce the same result when sent to the POSTMAN Echo API.  However, your API server may want the URL encoded string when special characters exist.  If so, there are several URL encoding & decoding functions posted to the forum.  Just do a search for URLEncode.

Example:

#include <Constants.au3>
#include <MyIncludes\json\json.au3>

http_post_example()

Func http_post_example()
    Local $oComErr   = Null
;~  Local $sPostData = 'username=myrealusername&password=]=oN9>fh2!O'
    Local $sPostData = 'username=myrealusername&password=%5D=oN9%3Efh2!O' ;URL Encoded

    ;Register COM Error Handler
    $oComErr = ObjEvent("AutoIt.Error", com_error_handler)
    If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", _
                               "Unable to register COM error handler - @error = " & @error)

    ;Send POST request using WINHTTP COM object
    With ObjCreate("winhttp.winhttprequest.5.1")

        ;Open POST request, set request header(s), and send the request
        .Open("POST", "https://postman-echo.com/post")
        If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", _
                                   StringFormat("(0x%X) %s", $oComErr.RetCode, $oComErr.WinDescription))

        .SetRequestHeader("Content-Type" , "application/x-www-form-urlencoded")
        .SetRequestHeader("Accept"       , "application/json")
        .SetRequestHeader("Cache-Control", "no-cache")

        .Send($sPostData)
        If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", _
                                   StringFormat("(0x%X) %s", $oComErr.RetCode, $oComErr.Description))

        ConsoleWrite(StringFormat("HTTP Status: %s (%s)", .Status, .StatusText) & @CRLF)

        ;If http status code not 200, exit with message
        If .Status <> 200 Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", _
                                           StringFormat("HTTP Status Code = %s %s", .Status, .StatusText))

        ;Display formatted JSON response
        ConsoleWrite(@CRLF & "HTTP Response:" & @CRLF)
        ConsoleWrite(Json_Encode(Json_Decode(.ResponseText), $JSON_PRETTY_PRINT + $JSON_UNESCAPED_SLASHES) & @CRLF)

    EndWith
EndFunc

Func com_error_handler($oError)
    With $oError
        ConsoleWrite(@ScriptName & " (" & .scriptline & ") : ==> COM Error intercepted !" & @CRLF)
        ConsoleWrite(@TAB & "Error Number........... " & "0x" & Hex(.number) & @CRLF)
        ConsoleWrite(@TAB & "Error WinDescription... " & StringStripWS(.windescription, $STR_STRIPTRAILING) & @CRLF)
        ConsoleWrite(@TAB & "Error Description...... " & StringStripWS(.description   , $STR_STRIPTRAILING) & @CRLF)
        ConsoleWrite(@TAB & "Error ScriptLine....... " & .scriptline & @CRLF)
        ConsoleWrite(@TAB & "Error RetCode.......... " & "0x" & Hex(.retcode) & @CRLF)
    EndWith

    Return ; Return so @error can be trapped by the calling function
EndFunc

Output:

HTTP Status: 200 (OK)

HTTP Response:
{
    "args": {},
    "data": "",
    "files": {},
    "form": {
        "username": "myrealusername",
        "password": "]=oN9>fh2!O"
    },
    "headers": {
        "x-forwarded-proto": "https",
        "x-forwarded-port": "443",
        "host": "postman-echo.com",
        "x-amzn-trace-id": "Root=1-62fc3310-05b42b003c0bbd127b09c301",
        "content-length": "44",
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded; Charset=UTF-8",
        "accept": "application/json",
        "user-agent": "Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)"
    },
    "json": {
        "username": "myrealusername",
        "password": "]=oN9>fh2!O"
    },
    "url": "https://postman-echo.com/post"
}

 

Edited by TheXman
Small readability changes to the example script
Posted (edited)

unfortunately the only documentation I have is the one I wrote
I tried your method (thank you very much) by entering the values of the server to which I have to send the POST and it comes back to me: "HTTP Status: 403 (Forbidden)"
At this point I am afraid that the problem now may be that they have not enabled me to make calls to their server.

I also tried with this script and the result is the same: 403 Forbidden

 

Global Const $HTTP_STATUS_OK = 200

$test = HttpPost("https://XXXXXXXXXXXXXXXXXXXXXXXX/api/login", "username=myrealusername&password=]=oN9>fh2!O")

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("Accept", "application/json")
    $oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")

    $oHTTP.Send($sData)
    If (@error) Then Return SetError(2, 0, 0)
    
    ConsoleWrite("$oHTTP.ResponseText= " & $oHTTP.ResponseText & @CRLF)
    
    If ($oHTTP.Status <> $HTTP_STATUS_OK) Then Return SetError(3, 0, 0)

    Return SetError(0, 0, $oHTTP.ResponseText)

EndFunc

Precisely it comes out written:

$oHTTP.ResponseText= {"code":403,"error":"User not found","message":"The provided username/password combination was not found."}

 

Edited by marcoauto
I added the server response
  • 3 months later...
Posted

For anyone who gets problems in GET or POST recently, the enforcing of TLS 1.2 encryption in most websites could be the problem.

I just recently fixed some computers that suddenly refused to do web requests. Those computers were all Win7. I used the following code to run on them:

Local $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
$oHTTP.open( "GET", "https://howsmyssl.com/a/check", False)
$oHTTP.Send()
ClipPut($oHTTP.responseText)

Then I paste the result in Notepad and read. The most important part is the last one: TLS Version. It should be using TLS 1.2. The ones using TLS 1.0 all got error results from the web services.

To fix that, first make sure the Win7 computer has the update KB3140245. It most likely has the update already.

Secondly, get the MS EasyFix51044 to apply it. Somehow my manual registry fix didn't work, but the EasyFix did.

Restart the computer, and the AutoIt code above should give you the TLS 1.2 now, even it says "bad" it's working.

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
  • Recently Browsing   0 members

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