Invoke-WebRequest : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse

Hi,

Am trying to execute the following script in my  windows power shell, but keep running into this error.

Can somebody help please?

$c1=$args[0]
$path=$args[1]
$cert=$args[2]
$p=$args[3]
$peid=$args[4]
$a2="AccountFN"


$body6="{`"provider`": {`"href`":`""+$path+"/providers/1`"},`"id`": `"$peid`",`"name`": `"+$a2+"`,`"description`": `"+$a2+"`}"

$r=Invoke-WebRequest -uri "$path/tenants/$c1/projects/$p/accounts" -Headers $headers -Certificate $cert -ContentType application/json -Method POST -Body $body6

Am using the Invoke-WebRequst to call an API which has both credential based authentication and SSL based authentication.

Am i doing something wrong?

Error Obtained:

Invoke-WebRequest : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.At C:\Windows\Temp\PO_WorkingDir_a432e8d1-d685-45e2-926d-351440a713ff\PO_PSScript_a432e8d1-d685-45e2-926d-351440a713ff.ps1:16 char:4+ $r=Invoke-WebRequest -uri "$path/tenants/$c1/projects/$p/accounts" -Headers $hea ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : NotSpecified: (:) [Invoke-WebRequest], ProtocolV    iolationException    + FullyQualifiedErrorId : System.Net.ProtocolViolationException,Microsoft.    PowerShell.Commands.InvokeWebRequestCom

July 20th, 2015 1:47am

The orginal JSON was something like this-

{

        provider: {

                href:https://{host}:{port}/providers/{providerId}

        },

        "id": string,

        "name": string,

        description: string

}

which i have handled in body6 variable, am i doing something wrong here?

Any help would be much appreciated!

Free Windows Admin Tool Kit Click here and download it now
July 20th, 2015 1:49am

This will help you straighten out issues with embedded quotes.

Param(
    [string]$c1,
    [string]$path,
    [string]$cert,
    [string]$p,
    [string]$peid,
    [string]$a2='AccountFN'
)
$headers=????
$uri = "$path/tenants/$c1/projects/$p/accounts"
$json=@'
{{    
"provider": {{
    "href":"{0}/providers/1"
    }},
    "id":"{1}",
    "name": "{2}",
   "description": "{2}" 
}}
'@
$body=$json -f $path,$peid,$a2
$r=Invoke-WebRequest -uri -Headers $headers -Certificate $cert -ContentType 'application/json' -Method POST -Body $body

July 20th, 2015 5:04am

Hello,

Apologies on missing the header.

$user = "admin"
$pass = "Password1"
$pair = "$($user):$($pass)"

$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)

$basicAuthValue = "Basic $base64"

$headers = @{ Authorization = $basicAuthValue

Thanks for the inputs.

Am having some trouble forming the json mentioned above.

$json=@'{{"provider": {{"href":"{0}/providers/1"}},"id":"{1}","name": "{2}","description": "{2}" }}'@

throws me an error back stating

At line:1 char:9
+ $json=@'{{"provider": {{"href":"{0}/providers/1"}},"id":"{1}","name": "{2}","des ...
+         ~
The character is not allowed after a here string header but before the end of the line.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedCharactersAfterHereStringHeader

Is there some kind of intendation to follow here?

Please let me know if you have faced such issues.

Free Windows Admin Tool Kit Click here and download it now
July 20th, 2015 5:51am

Why did you change it?  I posted the correct syntax and you broke it.  You cannot place @''@ on one line.

What makesyou think you can place the logon info into the header?  Use either Credential or Cert to authenticate.

All of this is up to the designers of the web service.  You need to contact them to learn how to use their API implementation.

July 20th, 2015 5:55am

Here is a more normal approach using REST:

http://www.lavinski.me/calling-a-rest-json-api-with-powershell/

http://www.jokecamp.com/blog/invoke-restmethod-powershell-examples/

Here is part of a working example:

$page=Invoke-WebRequest "http://maps.googleapis.com/maps/api/elevation/json?locations=32.000000,102.000000&sensor=false"
$page.content
$page.content|ConvertFrom-Json
($page.content|ConvertFrom-Json).Results

Free Windows Admin Tool Kit Click here and download it now
July 20th, 2015 6:27am

Thank you so much!

am trying to automate these scripts so that they run in a loop, without any manual intervention.

This script:

$json=@' {{ "provider": {{ "href":"{0}/providers/1" }}, "id":"{1}", "name": "{2}", "description": "{2}" }} '@

works just fine in my local, but will not work off automated scripts as the power shell doesnt realise its an end of script unless user types in an extra ENTER.

Is there any easier way to do this?

Any thoughts would be great!

July 21st, 2015 3:06am

No idea what you are posting about. A script is a script.  It does not need an enter except if there is an error in the script.

What script I it that is doing this.  Why have you changed the question.  A new question requires a new topic.

Free Windows Admin Tool Kit Click here and download it now
July 21st, 2015 6:34am

Rhis might be a bit confusing to understand.

Sorry if i confused you,

PFB SS of what i was trying to tell you:

Since it doesn't return back to the main drive again, my automated scripts are in running state only.

When i press 2 enters ON the keyboard this script,it returns to my main drive again

Was this embedding quotes the reason i get the "You must write ContentLength bytes to the request stream before calling [Begin]GetResponse"?

Any response here would be great!

Thanks a lot for the help already!

July 21st, 2015 6:45am

I repeat:

No idea what you are posting about. A script is a script.  It does not need an enter except if there is an error in the script.

What script I it that is doing this.  Why have you changed the question.  A new question requires a new topic.

Free Windows Admin Tool Kit Click here and download it now
July 21st, 2015 6:48am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics