get请求的基本排序:
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 >
如何输出原始JSON?或格式化?
答案 0 :(得分:2)
您可以使用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()
答案 1 :(得分:0)
您可以按如下方式获得原始回复
(Invoke-WebRequest http://ipinfo.io/json ).rawcontent
或解析JSON,然后选择您感兴趣的属性:
Invoke-WebRequest http://ipinfo.io/json | ConvertFrom-Json