难以从api访问JSON文件 - 接收403错误(但是从另一台服务器工作)

问题描述 投票:0回答:1

访问https://api.weather.gov/products/fead3465-2e6f-4350-ae90-15aaa61b91ff以检索JSON字符串时,我收到(403):Forbidden错误。相同的代码使用另一个URL(http://mesonet.agron.iastate.edu/json/nwstext_search.py?sts=2019-04-15T00:00Z&ets=2019-04-18T00:00Z&awipsid=PNSBOX)成功,但是,该URL不如api.weather.gov强大。

我不确定是否需要模拟浏览器凭据以从api访问此JSON。我正在使用Windows Powershell 2.0编写代码(遗憾的是无法升级)。

$url = "https://api.weather.gov/products/fead3465-2e6f-4350-ae90-15aaa61b91ff"  
$WebRequest = [System.Net.WebRequest]::Create($url)
$WebRequest.Method = "GET"
$WebRequest.ContentType = "application/json"
$WebRequest.UseDefaultCredentials = $true
$Response = $WebRequest.GetResponse()
$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$data = $ReadStream.ReadToEnd()

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
$ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$json = $ser.DeserializeObject($data)
echo $json

期待看到JSON,但得到(403):Forbidden错误。

json windows powershell powershell-v2.0
1个回答
0
投票

看看FAQ for this api,我看到他们提到了UserAgent。如果我指定另一个UserAgent,我能够让这个为我跑。我会检查他们的API许可证,以确保这是访问此API的有效/合法方式,以确保您不会违反其使用条款访问它。

$url = "https://api.weather.gov/products/fead3465-2e6f-4350-ae90-15aaa61b91ff"  
$WebRequest = [System.Net.WebRequest]::Create($url)
$WebRequest.Method = "GET"
$WebRequest.ContentType = "application/json"
$WebRequest.UserAgent = 'Mozilla/5.0 (Windows NT; Windows NT 6.1; en-US) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6'
$Response = $WebRequest.GetResponse()
$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$data = $ReadStream.ReadToEnd()

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
$ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$json = $ser.DeserializeObject($data)
echo $json
© www.soinside.com 2019 - 2024. All rights reserved.