使用 PowerShell 发起 HTTP REST请求

1、方法一,使用PowerShell 自带的命令 Invoke-WebRequest

例如:

Invoke-WebRequest http://localhost:8088/login -Method POST -ContentType "application/json" -Body '{"account":"ElasticSearch","password":"123456"}'

详细手册参考:

https://msdn.microsoft.com/powershell/reference/5.1/microsoft.powershell.utility/Invoke-RestMethod#example-2-perform-a-post-request

 

2、方法二,编写PowerShell 脚本

利用 System.Net.WebRequest,脚本示例如下:

## 文件名:http.ps1

## 先设置:set-ExecutionPolicy RemoteSigned

## 然后执行:.\http.ps1 -target "http://127.0.0.1:8088/login" -verb "POST" -content '{"account":"admin","password":"123456"}'

[CmdletBinding()]

Param(

    [Parameter(Mandatory=$True,Position=1)]

    [string] $target,

    [Parameter(Mandatory=$True,Position=2)]

    [string] $verb,      

    [Parameter(Mandatory=$False,Position=3)]

    [string] $content

)

write-host "Http Url: $target"

write-host "Http Verb: $verb"

write-host "Http Content: $content"

$webRequest = [System.Net.WebRequest]::Create($target)

$encodedContent = [System.Text.Encoding]::UTF8.GetBytes($content)

$webRequest.Method = $verb

write-host "UTF8 Encoded Http Content: $content"

if($encodedContent.length -gt 0) {

    $webRequest.ContentType = "application/json"

    $webRequest.ContentLength = $encodedContent.length

    $requestStream = $webRequest.GetRequestStream()

    $requestStream.Write($encodedContent, 0, $encodedContent.length)

    $requestStream.Close()

}

[System.Net.WebResponse] $resp = $webRequest.GetResponse();

if($resp -ne $null) 

{

    $rs = $resp.GetResponseStream();

    [System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;

    [string] $results = $sr.ReadToEnd();

    return $results

}

else

{

    exit ''

}

保存文件:http.ps1

然后运行:.\http.ps1 -target "http://127.0.0.1:8088/login" -verb "POST" -content '{"account":"admin","password":"123456"}'

注意,在Powershell直接脚本时会出现:

无法加载文件 ******.ps1,因为在此系统中禁止执行脚本。有关详细信息,请参阅 "get-help about_signing"。 

解决方案如下:

命令窗口输入:set-ExecutionPolicy RemoteSigned

参见:http://www.jb51.net/article/95022.htm

详细参考微软.NET的手册:https://msdn.microsoft.com/zh-cn/library/system.net.webrequest_methods(v=vs.110).aspx

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值