基本的获取请求:
thufir >
thufir >
thufir > $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.8762
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
thufir >
thufir > type .foo.ps1
"start"
$request = [System.Net.WebRequest]::Create("http://ipinfo.io/json")
$request.Method = "GET"
[System.Net.WebResponse]$response = $request.GetResponse()
$response
"done"
thufir >
thufir > .foo.ps1
start
IsMutuallyAuthenticated : False
Cookies : {}
Headers : {Vary, x-cloud-trace-context, Access-Control-Allow-Or
igin, X-Content-Type-Options...}
ContentLength : 173
ContentEncoding :
ContentType : application/json; charset=utf-8
CharacterSet : utf-8
Server :
LastModified : 29/03/2018 7:54:31 AM
StatusCode : OK
StatusDescription : OK
ProtocolVersion : 1.1
ResponseUri : http://ipinfo.io/json
Method : GET
IsFromCache : False
done
thufir >
thufir >
如何输出RAW JSON?或格式化?
您可以使用WebClient
将JSON下载为字符串:
$wc = New-Object System.Net.WebClient
$json = $wc.DownloadString("http://ipinfo.io/json")
要使用Webresponse,您将需要Ex。StreamReader
读取响应。例如:
$request = [System.Net.WebRequest]::Create("http://ipinfo.io/json")
#GET is default
#$request.Method = "GET"
$response = $request.GetResponse()
$reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $response.GetResponseStream(), $response.CharacterSet
#Get JSON response
$JSON = $reader.ReadToEnd()
#Cleanup
$reader.Close()
$response.Close()
您可以按以下方式获取原始响应
(Invoke-WebRequest http://ipinfo.io/json ).rawcontent
或解析JSON,然后选择您感兴趣的属性:
Invoke-WebRequest http://ipinfo.io/json | ConvertFrom-Json