call webservice in powershell
- User
call webservice in powershell
- Assistant
To call a webservice in PowerShell, follow these steps:
- Import the "System.Net" namespace:
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12- Create a new instance of the "WebRequest" class:
$request = [System.Net.WebRequest]::Create("<webservice URL>")- Set the "ContentType" property of the request object to "application/json":
$request.ContentType = "application/json"- Set the "Method" property of the request object to "POST":
$request.Method = "POST"- Create a JSON object to send to the webservice:
$json = '{"param1": "value1", "param2": "value2"}'- Convert the JSON object to a byte array:
$data = [System.Text.Encoding]::UTF8.GetBytes($json)- Set the "ContentLength" property of the request object to the length of the byte array:
$request.ContentLength = $data.Length- Write the byte array to the request stream:
$stream = $request.GetRequestStream()$stream.Write($data, 0, $data.Length)$stream.Close()- Get the response from the webservice:
$response = $request.GetResponse()- Read the response stream:
$streamReader = New-Object System.IO.StreamReader($response.GetResponseStream())$result = $streamReader.ReadToEnd()- Close the response stream:
$streamReader.Close()- Parse the JSON response:
$jsonResponse = ConvertFrom-Json $result- Use the parsed JSON data as needed.
Note: Replace "" with the actual URL of the webservice to be called. Also, modify the JSON object as needed to include the correct parameters and values.