试着在powershell v2.0中做一个简单的帖子请求,没有运气

时间:2015-12-22 18:29:36

标签: powershell

我只是尝试使用一些键和值来执行HTTP POST请求。我不能让这个为我的生活而工作,是的,我知道这应该很简单。

以下是我尝试的内容:

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

这在Powershell v2.0中不起作用,因为我收到了错误

  

方法   调用失败,因为[System.Net.HttpWebRequest]不包含   一个名为' CreateHttp'。

的方法

接下来,我采取了其他人的例子:

$URI1 = "http://mysite/test.php"

$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$body = "username=test"

# $request | Get-Member  for a list of methods and properties 

try
{
    $requestStream = $request.GetRequestStream()
    $streamWriter = New-Object System.IO.StreamWriter($requestStream)
    $streamWriter.Write($body)
}

finally
{
    if ($null -ne $streamWriter) { $streamWriter.Dispose() }
    if ($null -ne $requestStream) { $requestStream.Dispose() }
}

$res = $request.GetResponse()

但出于某种原因"用户名" test.php echos $ _POST ['用户名']

时没有注意到

有人可以帮我告诉我我在这里失踪了吗?我已经谷歌搜索了几个小时,我尝试的一切都不是因为某种原因而工作。适用于大于2.0但不是2.0的Powershell版本(Windows 7中的默认值)。

Invoke-WebRequest和Invoke-RestMethod在Powershell v2.0上不起作用,所以我不得不找到所有这些烦人的替代方案。

*编辑*

我在找到另一个HTTP POST请求示例后得到了它的工作:

$url = "http://mysite/test.php"
$postData = "username=test"

$buffer = [text.encoding]::ascii.getbytes($postData)

[net.httpWebRequest] $req = [net.webRequest]::create($url)
$req.method = "POST"
$req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
$req.Headers.Add("Accept-Language: en-US")
$req.Headers.Add("Accept-Encoding: gzip,deflate")
$req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
$req.AllowAutoRedirect = $false
$req.ContentType = "application/x-www-form-urlencoded"
$req.ContentLength = $buffer.length
$req.TimeOut = 50000
$req.KeepAlive = $true
$req.Headers.Add("Keep-Alive: 300");
$reqst = $req.getRequestStream()
$reqst.write($buffer, 0, $buffer.length)
$reqst.flush()
$reqst.close()
[net.httpWebResponse] $res = $req.getResponse()
$resst = $res.getResponseStream()
$sr = new-object IO.StreamReader($resst)
$result = $sr.ReadToEnd()
$res.close()

这是在另一个网站上发现之前发表的其他评论;但是,我已经尝试过以下人们提出的解决方案的解决方案,并且能够实现这一点。

2 个答案:

答案 0 :(得分:2)

在第一个示例代码中,该方法应命名为Create,而不是CreateHttp

在第二个代码块中,您将内容类型设置为' application / xml',但正文是纯文本。

答案 1 :(得分:1)

此方法和您的初始示例本身可以在较新版本的PowerShell中使用。尝试在您的系统上安装dotnet 4.5,然后安装WMF 4.0,这应该没有问题。

[System.Net.HttpWebRequest]的dotnet类没有静态方法CreateHttp(),直到dotnet 4.5为seen here on MSDN Docs

为什么不将这台计算机更新为较新版本的PowerShell?这将是一个不那么痛苦。