使用 PowerShell 发起 HTTP REST请求

栏目: 后端 · 前端 · 发布时间: 5年前

内容简介:1、方法一,使用PowerShell 自带的命令 Invoke-WebRequest例如:Invoke-WebRequest http://localhost:8088/login -Method POST -ContentType "application/json" -Body '{"account":"ElasticSearch","password":"123456"}'

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

群体的智慧

群体的智慧

[美] 詹姆斯·索罗维基 / 王宝泉 / 中信出版社 / 2010-10 / 33.00元

《纽约时报》榜首畅销书,《商业周刊》《福布斯》杂志最佳商业图书 21世纪商务人士必读书,了解群体智慧时代的决策模式 告诉我们如何过日子、如何选择领导人、如何做生意以及如何思考这个世界 我们当中的大多数人,不论是选民还是投资者,是客户还是经理人,似乎都相信宝贵的知识掌握在少数人手中,认为精英们做出的决策更加聪明,很少有人相信“乌合之众”也能像专家那样做得如此出色。 但《纽约客......一起来看看 《群体的智慧》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具