invoke-webrequest 请求以及下载有问


PowerShell交流中心分类: Questionsinvoke-webrequest 请求以及下载有问
0
zsnmwy asked 5年 ago


http://steamworkshopdownloader.com/api/workshop/1266052762


http://steamworkshopdownloader.com/api/workshop/1383841968
 
请问为啥一样是请求api ,返回json
而另一个会报错呢?
 
还有使用
invoke-webrequest
下载的时候,如何才能够自动把文件保存成 服务器那边给的文件名呢?
而不是自己手动指定
因为我现在用的下载方式是这样的

Invoke-WebRequest $file_url -OutFile "$file_path\max.zip"

刚刚接触powershell,有点懵逼
 

1 Answers
0
Best Answer
Mooser Lee 管理员 answered 5年 ago
  • 问题1,报错不是来自PowerShell,是远程服务器针对这个资源,给出的响应状态码为403,内容为:{ “message”: “The game that this item belongs too does not allow downloading of its items…BUMMER!” }
  • 问题2:服务端给出的文件名一般会放在header中,你先请求一次,只请求header,得到文件名后,再下载文件。下载时,再指定文件名。
    $headRequest = Invoke-WebRequest https://steamusercontent-a.akamaihd.net/ugc/936064212973533787/32285B2A997B209DB8A31E87FD991D6B8066F5A8/ -Method Head
    $headRequest.Headers['Content-Disposition'].Split("';",[System.StringSplitOptions]::RemoveEmptyEntries) | select -Last 1
    
zsnmwy replied 5年 ago

那么有什么办法拿到返回的这个message
我想把这个message后面的值拿到,然后输出。
因为现在返回403之后,$i拿不到数据。

Mooser Lee 管理员 replied 5年 ago

这里有一篇文你需要阅读一下,理解终止错误和非终止错误:https://www.pstips.net/terminating-errors-and-non-terminating-errors.html 。然后你的问题可以这样解决。

try {
        $result = Invoke-WebRequest http://steamworkshopdownloader.com/api/workshop/1383841968
}
catch {
        $result = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($result)
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd();
	$responseBody | ConvertFrom-Json | Select-Object -ExpandProperty message
}
zsnmwy replied 5年 ago

好的,谢谢