首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell WebRequest POST

PowerShell WebRequest POST
EN

Stack Overflow用户
提问于 2014-04-08 03:39:17
回答 2查看 55.4K关注 0票数 11

在WindowsCmdlet3.0中引入了Invoke-RestMethod PowerShell。

Invoke-RestMethod cmdlet接受用于设置请求正文的-Body<Object>参数。

由于某些限制,在我们的案例中不能使用Invoke-RestMethod cmdlet。另一方面,文章InvokeRestMethod for the Rest of Us中描述的另一种解决方案适合我们的需求:

代码语言:javascript
复制
$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参数)发送请求正文?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-08 04:13:04

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

代码语言:javascript
复制
$request.Method= 'POST';

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

代码语言:javascript
复制
$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();

NOTEPowerShell Core版本现在在GitHub上是开源的,并且在Linux、Mac和Windows上是跨平台的。应在此项目的GitHub问题跟踪器上报告与Invoke-RestMethod cmdlet有关的任何问题,以便可以跟踪和修复这些问题。

票数 20
EN

Stack Overflow用户

发布于 2015-03-18 07:11:35

代码语言:javascript
复制
$myID = 666;
#the xml body should begin on column 1 no indentation.
$reqBody = @"
<?xml version="1.0" encoding="UTF-8"?>
<ns1:MyRequest
    xmlns:ns1="urn:com:foo:bar:v1"
    xmlns:ns2="urn:com:foo:xyz:v1"
    <ns2:MyID>$myID</ns2:MyID>
</ns13:MyRequest>
"@

Write-Host $reqBody;

try
{
    $endPoint = "http://myhost:80/myUri"
    Write-Host ("Querying "+$endPoint)
    $wr = [System.Net.HttpWebRequest]::Create($endPoint)
    $wr.Method= 'POST';
    $wr.ContentType="application/xml";
    $Body = [byte[]][char[]]$reqBody;
    $wr.Timeout = 10000;

    $Stream = $wr.GetRequestStream();

    $Stream.Write($Body, 0, $Body.Length);

    $Stream.Flush();
    $Stream.Close();

    $resp = $wr.GetResponse().GetResponseStream()

    $sr = New-Object System.IO.StreamReader($resp) 

    $respTxt = $sr.ReadToEnd()

    [System.Xml.XmlDocument] $result = $respTxt
    [String] $rs = $result.DocumentElement.OuterXml
    Write-Host "$($rs)";
}
catch
{
    $errorStatus = "Exception Message: " + $_.Exception.Message;
    Write-Host $errorStatus;
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22921529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档