Okrx Okrx - 9 months ago 79
reST (reStructuredText) Question

Invoke-RestMethod and Fiddler, can't get 200 code in return

I am trying to replicate a POST call that can be send from GUI using Invoke-RestMethod. I would like to automate it and have been trying to use powershell to do it.

It alwasy returns 202 code, have been trying it for a few hours now but can't progress. This is really the first time I am playing with invoke-restmedod and Rest so please be detailed what's wrong. Any help is highly appreciated.

So the successful call captured by Fiddler is this:

enter image description here

enter image description here

The powershell code is:

$WfManDirUserPass = "Password"
$secpasswd = ConvertTo-SecureString $WfManDirUserPass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("admin", $secpasswd)

$active = @{
$json = $active | ConvertTo-Json

$response = invoke-restmethod -uri https://myhost/MAM/wfservice/workers/?ip="&"port="&"newStatus=Deactivating -Method POST -Body $json -Credential $cred -ContentType 'application/json'
} catch {
write-host("Sorry, it does not work")

This powershell code in Fiddler returns:

enter image description here
enter image description here

I can see that the JSON is not exactly the same on the attached images. However I stuck now and would really appreciate some help now.

Answer Source

This is a reply from 1RedOne (Reddit) user that helped me out:

  1. For one, let's wrap your whole -URI in single quotes and remove the double quotes. Your URL is probably messed up, which isn't helping things.

    $uri = 'https://myhost/MAM/wfservice/workers/?ip=&port=&newStatus=Deactivating' 

    $response = invoke-restmethod -uri $uri-Method POST -Body $json -Credential $cred -ContentType 'application/json'

2. Furthermore, your call from fiddler uses basic authentication, and is probably incompatible with using a -Credential object. Try replacing your credentials with this format.

$user = "yourusername"
$pass = 'yourPassWord'

# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))

# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))

Then, reference the $header object within your Invoke-RestMethod, like so.

$response = invoke-restmethod -uri $uri- Method POST `
   -Body $json -Header $headers -ContentType 'application/json'

That's it. It worked like a charm!