3

What I am currently doing:

Invoke-WebRequest -Uri https://coolWebsite.com/ext/ext -ContentType application/json -Method POST -Body $someJSONFile

I am looking for a way to POST this same .json file in Powershell without using Invoke-WebRequest, if it is possible. This new method would preferably allow me to get the server output content and parse through it in powershell.

Maybe by calling an outside cURL method? I really am not sure and all my internet research has proved fruitless.

How can I achieve this above result without Invoke-WebRequest?

5
  • not sure if this will help, but it helped me do something similar previously: blogs.technet.com/b/heyscriptingguy/archive/2012/10/08/… Commented Jun 26, 2014 at 17:15
  • Hm. That is an interesting blog post but it kind of skips over the part - if it's even included - where the json is actually uploaded to a url. Commented Jun 26, 2014 at 17:22
  • Yeah, like i said, it helped me get over my issue, but I was hoping it would give you some insight as to how you might accomplish it. Commented Jun 26, 2014 at 17:30
  • 1
    You can capture the content returned by the server on a POST when using invoke-webrequest. Is that your only reason for not using what's provided with PowerShell? How about System.Net.WebClient? Commented Jun 26, 2014 at 17:52
  • 3
    @alroc No, I was having problems integrating this with TeamCity. I found a solution: Invoke-RestMethod -Uri coolWebsite.com -ContentType application/json -Method POST -Body $someFile Commented Jun 26, 2014 at 20:52

2 Answers 2

3

You can try this :

# RestRequest.ps1

Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization, System.Web.Extensions

$utf8 = [System.Text.Encoding]::UTF8

function Request-Rest
{
  [CmdletBinding()]
  PARAM (
         [Parameter(Mandatory=$true)]
         [String] $URL,

         [Parameter(Mandatory=$false)]
         [System.Net.NetworkCredential] $credentials,

         [Parameter(Mandatory=$true)]
         [String] $JSON)

  # Remove NewLine from json
  $JSON = $JSON -replace "$([Environment]::NewLine) *",""  

  # Create a URL instance since the HttpWebRequest.Create Method will escape the URL by default.   
  # $URL = Fix-Url $Url
  $URI = New-Object System.Uri($URL,$true)   

  try
  {
    # Create a request object using the URI   
    $request = [System.Net.HttpWebRequest]::Create($URI)   
    # Build up a nice User Agent   
    $UserAgent = "My user Agent"
    $request.UserAgent = $("{0} (PowerShell {1}; .NET CLR {2}; {3})" -f $UserAgent, $(if($Host.Version){$Host.Version}else{"1.0"}),  
                           [Environment]::Version,  
                           [Environment]::OSVersion.ToString().Replace("Microsoft Windows ", "Win"))

    $request.Credentials = $credentials
    $request.KeepAlive = $true
    $request.Pipelined = $true
    $request.AllowAutoRedirect = $false
    $request.Method = "POST"
    $request.ContentType = "application/json"
    $request.Accept = "application/json"

    $utf8Bytes = [System.Text.Encoding]::UTF8.GetBytes($JSON)
    $request.ContentLength = $utf8Bytes.Length
    $postStream = $request.GetRequestStream()
    $postStream.Write($utf8Bytes, 0, $utf8Bytes.Length)
    #Write-String -stream $postStream -string $JSON
    $postStream.Dispose()

    try
    {
      #[System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $request.GetResponse()
      $response = $request.GetResponse()
    }
    catch
    {
      $response = $Error[0].Exception.InnerException.Response; 
      Throw "Exception occurred in $($MyInvocation.MyCommand): `n$($_.Exception.Message)"
    }

    $reader = [IO.StreamReader] $response.GetResponseStream()  
    $output = $reader.ReadToEnd()  

    $reader.Close()  
    $response.Close()
    Write-Output $output  
  }
  catch
  {
    $output = @"
    {
      "error":1,
      "error_desc":"Error : Problème d'accès au serveur $($_.Exception.Message)"
    }
"@    
    Write-Output $output
  }
}

Edited 19-10-2015

Here is an example usage :

#$urlBase = "http://192.168.1.1:8080/" 

#######################################################################
#                           Login                                     #
#######################################################################
$wsLogin = "production/login"
Function login
{
  [CmdletBinding()]
  PARAM
  (
    [ValidateNotNullOrEmpty()]
    [String] $login,
    [String] $passwd
  )

  Write-Verbose $wsLogin 
  #$jsonIn = [PSCustomObject]@{"login"=$login;"passwd"=$passwd} | ConvertTo-Json
  $jsonIn = @"
  {
    "login":"$login",
    "passwd":"$passwd"
  }
"@
  Write-Verbose $jsonIn
  $jsonOut = Request-Rest -URL "$urlBase$wsLogin" -JSON $jsonIn -credentials $null
  Write-Verbose $jsonOut
  #return $jsonOut | ConvertFrom-Json 
  return $jsonOut
}
Sign up to request clarification or add additional context in comments.

1 Comment

@JBlanc, can you give an example of JSON?
-2

It is easy to convert that code to cURL

curl -v --insecure -X POST -H "Content-Type: application/json" --data-binary someJSONFile.js https://coolWebsite.com/ext/ext/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.