You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Invoke-WebRequest返回整数列表而非JSON,如何解码响应内容?

解决PowerShell中Brotli编码响应的解码问题

问题原因

使用Invoke-WebRequest -UseBasicParsing时,PowerShell不会自动处理**Brotli(br)**编码的响应(仅默认支持gzip/deflate解码),此时$response.Content会返回原始字节对应的整数数组,而非解码后的JSON文本。

解决方案步骤

1. 将整数列表转换为字节数组

如果$response.Content输出的是整数列表,先把它转成字节数组:

$bytes = [byte[]]$response.Content

2. 用BrotliStream解码字节数组

借助.NET的BrotliStream类完成解码:

using namespace System.IO
using namespace System.IO.Compression

# 把字节数据存入内存流
$memoryStream = New-Object MemoryStream($bytes)
# 创建Brotli解码流
$brotliStream = New-Object BrotliStream($memoryStream, [CompressionMode]::Decompress)
# 读取解码后的内容
$streamReader = New-Object StreamReader($brotliStream)
$decodedJson = $streamReader.ReadToEnd()

# 释放资源
$streamReader.Close()
$brotliStream.Close()
$memoryStream.Close()

3. 处理解码后的JSON

现在$decodedJson就是正常的JSON字符串,可直接输出或转换为PowerShell对象:

# 输出JSON文本
Write-Output $decodedJson
# 转换为PowerShell对象
$jsonObject = $decodedJson | ConvertFrom-Json

额外优化:清理无效请求头

Chrome复制的脚本里包含method、authority、scheme、path这些冗余头,它们是Chrome内部的请求元数据,PowerShell的Invoke-WebRequest不需要这些字段,建议删除以避免请求异常。修改后的Headers部分如下:

-Headers @{
   "sec-ch-ua"="`"Chromium`";v=`"94`", `"Google Chrome`";v=`"94`", `";;Not A Brand`";v=`"99`""
   "accept"="application/vnd.api+json"
   "authorization"="Bearer $($token.Token)"
   "sec-ch-ua-mobile"="?0"
   "sec-ch-ua-platform"="`"Windows`""
   "origin"="https://xx.com"
   "sec-fetch-site"="same-site"
   "sec-fetch-mode"="cors"
   "sec-fetch-dest"="empty"
   "referrer"="https://xx.com/"
   "accept-encoding"="gzip, deflate, br"
   "accept-language"="en-US,en;q=0.9"
 }

注意事项

该方法依赖.NET对Brotli的支持:.NET Core 2.1及以上、.NET Framework 4.8及以上版本默认支持;若使用PowerShell 5.1搭配.NET Framework 4.7及以下,需手动引入Brotli相关库。

内容的提问来源于stack exchange,提问作者ca9163d9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:24:33