How to pass json in HttpRequestMessage

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);




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