Making a PowerShell POST request if a body param starts with '@'

后端 未结 3 790
借酒劲吻你
借酒劲吻你 2020-11-30 03:18

I want to make a POST request in PowerShell. Following is the body details in Postman.

{
  \"@type\":\"login\",
  \"username\":\"xxx@gmail.com\",
  \"passwor         


        
3条回答
  •  清歌不尽
    2020-11-30 03:47

    Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

    $JSON = @'
    {"@type":"login",
     "username":"xxx@gmail.com",
     "password":"yyy"
    }
    '@
    
    $response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
    

    If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

    $response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
    

    If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

    $JSON = @{
        "@type" = "login"
        "username" = "xxx@gmail.com"
        "password" = "yyy"
    } | ConvertTo-Json
    

提交回复
热议问题