How to pass json in HttpRequestMessage

Welcome Forums General PowerShell Q&A How to pass json in HttpRequestMessage

Viewing 1 reply thread
  • Author
    • #211425
      Topics: 1
      Replies: 0
      Points: 11
      Rank: Member

      Hi Friends,


      I am having some issues while sending json message in HttpRequestMessage.

      The content part of HttpRequestMessage is expecting data to be in System.Net.Http.HttpContent format , and i am not able to convert from json to HttpContent fromat.


      I tried converting to object and then assigning it to content but that is also not working .’


      $TEST = $<My Json Data>| ConvertFrom-Json

      $HttpRequestMessage = New-Object System.Net.Http.HttpRequestMessage
      $HttpRequestMessage.Method = “POST”
      $HttpRequestMessage.RequestUri = “<My Url Here >”
      $HttpRequestMessage.Headers.Add([System.Net.HttpRequestHeader]::ContentType, “application/json”)
      $HttpRequestMessage.Headers.Add(‘api-key’, “<My Api Key >”)
      $HttpRequestMessage.Content = $TEST

      $HttpClient = New-Object System.Net.Http.HttpClient
      $HttpResponseMessage = $HttpClient.SendAsync($HttpRequestMessage);




    • #211566
      Topics: 12
      Replies: 1622
      Points: 2,560
      Helping Hand
      Rank: Community Hero

      Using the HTTPClient is an older way to do it as there is Invoke-WebRequest and Invoke-RestMethod that are wrappers for making these calls. They handle some of these conversion from a PSObject to JSON, but if you have complex bodies, you can convert it (e.g. $body | ConvertTo-Json -Depth 5). In your example, this appears to be wrong as Content is most likely a string value which should be straight JSON:

      $TEST = $<My Json Data>| ConvertFrom-Json

      But, using Invoke-RestMethod has examples for what you are most likely trying to do, but here is a basic example:

      $body = @{
          firstName = 'John'
          lastName  = 'Smith'
      $params = @{
          Method      = 'POST'
          Uri         = 'https://myapi/v2/Users'
          Headers     = @{'api-key' = '794f3793-7655-454c-b87a-1163e67a2314'}
          ContentType = 'application\json'
          Body        = $body
      $response = Invoke-RestMethod @params
Viewing 1 reply thread
  • You must be logged in to reply to this topic.