【PowerShell】Invoke-WebRequest和Invoke-RestMethod
  W7xauqsNtuHG 2023年11月02日 72 0

## Public free Restful API URL  

## https://documenter.getpostman.com/view/8854915/Szf7znEe#intro


# Example01

# --------------------------------------------------------------

$url = "https://cat-fact.herokuapp.com/facts/"

$r = Invoke-WebRequest -Uri $url

$r.GetType()

$result = ConvertFrom-Json -InputObject $r.Content

$result.GetType()

$result[0]



# Example02

# --------------------------------------------------------------

$url1 = "https://api.apis.guru/v2/list.json"

$r1 = Invoke-RestMethod -Uri $url1


# Example03

# --------------------------------------------------------------

# Invoke-WebRequest vs. Invoke-RestMethod

当我们对某个网站的探索中,如果您没有相关的文档,使用Invoke-WebRequest 是一个很好的开始。

假设我们使用两个命令连接到同一个网站,

其中变量 $web 使用 Invoke-WebRequest ;

而 $Rest 使用 Invoke-RestMethod。

$url2 = "https://www.baidu.com"

$web = Invoke-WebRequest -Uri $url2

$rest = Invoke-RestMethod -Uri $url2

$web



PS C:\Users\Administrator> $web



StatusCode        : 200

StatusDescription : OK

Content           : <html>

                    <head>

                    	<script>

                      location.replace(location.href.replace("https://","http://"));

                    	</script>

                    </head>

                    <body>

                    	<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></...

RawContent        : HTTP/1.1 200 OK

                    Connection: keep-alive

                    Accept-Ranges: bytes

                    Content-Length: 227

                    Cache-Control: no-cache

                    Content-Type: text/html

                    Date: Mon, 17 Jan 2022 02:39:23 GMT

                    P3P: CP=" OTI DSP COR IVA OUR...

Forms             : {}

Headers           : {[Connection, keep-alive], [Accept-Ranges, bytes], [Content-Length, 227], [Cache-Control, no-cache]...}

Images            : {}

InputFields       : {}

Links             : {}

ParsedHtml        : mshtml.HTMLDocumentClass

RawContentLength  : 227





PS C:\Users\Administrator>

#>

$rest

<#

PS C:\Users\Administrator> $rest

<html>

<head>

	<script>

  location.replace(location.href.replace("https://","http://"));

	</script>

</head>

<body>

	<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>

</body>

</html>


PS C:\Users\Administrator>  
#>

$web.Content -eq $rest


PS C:\Users\Administrator> $web.Content -eq $rest

True


PS C:\Users\Administrator>  

# Invoke-RestMethod 更擅长处理 XML 和 JSON 结果,而 Invoke-WebRequest 更擅长处理直接的 HTML 结果。


【PowerShell】Invoke-WebRequest和Invoke-RestMethod_Powershell








【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
W7xauqsNtuHG