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

后端 未结 3 758
借酒劲吻你
借酒劲吻你 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:44

    @Frode F. gave the right answer.

    By the Way Invoke-WebRequest also prints you the 200 OK and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod which is lighter.

    Also, keep in mind that you need to use | ConvertTo-Json for the body only, not the header:

    $body = @{
     "UserSessionId"="12345678"
     "OptionalEmail"="MyEmail@gmail.com"
    } | ConvertTo-Json
    
    $header = @{
     "Accept"="application/json"
     "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
     "Content-Type"="application/json"
    } 
    
    Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
    

    and you can then append a | ConvertTo-HTML at the end of the request for better readability

    0 讨论(0)
  • 2020-11-30 03:45

    You should be able to do the following:

    $params = @{"@type"="login";
     "username"="xxx@gmail.com";
     "password"="yyy";
    }
    
    Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params
    

    This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

    Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"
    

    Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题