Jam*_*mes 33 windows powershell web http api
我已经成功地使用Invoke-WebRequest从 PowerShell 向基于 REST 的 API 发布请求。
Invoke-WebRequest -UseBasicParsing https://my-rest-api.com/endpoint -ContentType "application/json" -Method POST -Body $json
Run Code Online (Sandbox Code Playgroud)
今天我遇到了Invoke-RestMethod听起来更贴切地命名我正在做的事情。有什么区别,是否有理由使用一个而不是另一个?
Dan*_*l B 38
您可以通过反编译Microsoft.PowerShell.Commands.Utility程序集来查找。
基本上,Invoke-WebRequest不会处理那么多的数据解析。使用-UseBasicParsing,它会执行一些基于正则表达式的 HTML 解析。如果没有此开关,它将使用 Internet Explorer COM API 来解析文档。
就是这样。它总是会尝试解析 HTML。
Invoke-RestMethod另一方面,有支持 JSON 和 XML 内容的代码。它将尝试检测适当的解码器。它不支持HTML(除了XML兼容HTML,当然)。
两者共享相同的核心逻辑来发出实际的 HTTP 请求。它们仅在结果处理上有所不同。
眼见为实!
PS C:\Users\fuzzy> (Invoke-RestMethod https://httpbin.org/headers).headers
Connection Host User-Agent
---------- ---- ----------
close httpbin.org Mozilla/5.0 (Windows NT; Windows NT 10.0; de-DE) WindowsPowerShell/5.1.15063.483
PS C:\Users\fuzzy> Invoke-WebRequest -UseBasicParsing https://httpbin.org/headers
StatusCode : 200
StatusDescription : OK
Content : {
"headers": {
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT; Windows NT 10.0; de-DE)
WindowsPowerShell/5.1.15063.483"
}
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Processed-Time: 0.00075101852417
Content-Length: 180
Content-Type: application/json...
Forms :
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [X-Processed-Time, 0.00075101852417]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml :
RawContentLength : 180
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33351 次 |
| 最近记录: |