PowerShell WebRequest POST [英] PowerShell WebRequest POST

查看:64
本文介绍了PowerShell WebRequest POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows PowerShell 3.0 中引入了 Invoke-RestMethod cmdlet.

In Windows PowerShell 3.0 was introduced Invoke-RestMethod cmdlet.

Invoke-RestMethod cmdlet 接受 -Body用于设置请求正文的参数.

Invoke-RestMethod cmdlet accepts -Body<Object> parameter for setting the body of the request.

由于某些限制,Invoke-RestMethod cmdlet 无法在我们的案例中使用.另一方面,文章 我们其他人的 InvokeRestMethod 适合我们的需求:

Due to a certain limitations Invoke-RestMethod cmdlet could not be used in our case. From the other hand, an alternative solution described in article InvokeRestMethod for the Rest of Us suits our needs:

$request = [System.Net.WebRequest]::Create($url)
$request.Method="Get"
$response = $request.GetResponse()
$requestStream = $response.GetResponseStream()
$readStream = New-Object System.IO.StreamReader $requestStream
$data=$readStream.ReadToEnd()
if($response.ContentType -match "application/xml") {
    $results = [xml]$data
} elseif($response.ContentType -match "application/json") {
    $results = $data | ConvertFrom-Json
} else {
    try {
        $results = [xml]$data
    } catch {
        $results = $data | ConvertFrom-Json
    }
}
$results 

但它仅用于 GET 方法.您能否建议如何扩展此代码示例,使其能够使用 POST 方法发送请求正文(类似于 Invoke-RestMethod<中的 Body 参数)/code>)?

But it is intended for a GET method only. Could you please suggest how to extend this code sample with the ability to send the body of the request using POST method (similar to Body parameter in Invoke-RestMethod)?

推荐答案

首先,更改更新 HTTP 方法的行.

First, change the line that updates the HTTP method.

$request.Method= 'POST';

接下来,您需要将消息正文添加到 HttpWebRequest 对象.为此,您需要获取对请求流的引用,然后向其中添加数据.

Next, you need to add the message body to the HttpWebRequest object. To do that, you need to grab a reference to the request stream, and then add data to it.

$Body = [byte[]][char[]]'asdf';
$Request = [System.Net.HttpWebRequest]::CreateHttp('http://www.mywebservicethatiwanttoquery.com/');
$Request.Method = 'POST';
$Stream = $Request.GetRequestStream();
$Stream.Write($Body, 0, $Body.Length);
$Request.GetResponse();

注意:PowerShell Core 版本现已在 GitHub 上开源,在 Linux、Mac 和 Windows 上跨平台.Invoke-RestMethod cmdlet 的任何问题都应在此项目的 GitHub 问题跟踪器上报告,以便对其进行跟踪和修复.

NOTE: PowerShell Core edition is now open source on GitHub, and cross-platform on Linux, Mac, and Windows. Any issues with the Invoke-RestMethod cmdlet should be reported on the GitHub issue tracker for this project, so they can be tracked and fixed.

这篇关于PowerShell WebRequest POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆