PowerShell调用API分页时Base64参数非法字符问题求助
我使用PowerShell的Invoke-WebRequest调用API,将返回结果转成JSON格式存入$response数组中。由于接口每次仅返回固定数量的结果,需要把首次响应里的Base64分页字符串传入后续请求。
响应中的分页格式示例:
"pagination":{"next":"H4sIAAAAAAAAAG2O2wqDMBBE/2Uei5bYVrz8ioiscUMDVm2SQkXy712FQh/6OsyZORuMHQM71BtoGlA3GxY3L+zCihrPF7v1HNaFPRLsMYVZyuC39cEjJhumOez0DzVYT/3IQ0fhPxXbmMDPLhx/Vm5BXiO2kjI5fe/IHFIHGDFRlMqkdOE8vXFPaaVykypd6aqgorgOJYQb7cPKXKaUSr4uVqxl4iQS8tHGD4B6x6ntAAAA","limit":1000,"total":9000}
手动复制该Base64字符串到代码中请求正常,但用以下代码自动获取并传入时:
$response = Invoke-WebRequest -Uri 'https://cloud.apiiuse.com/api/v3/assets/' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"limit":1000,"next":"($Response.Content|ConvertFrom-Json).Pagination.Next"}' -UseBasicParsing
会报如下错误:
Invoke-WebRequest : {"error":"Illegal base64 character 28"}
即使尝试用ToString()转换,错误依旧:
$response = Invoke-WebRequest -Uri 'https://cloud.apiiuse.com/api/v3/assets/' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"limit":1000,"next":"((($Response.Content|ConvertFrom-Json).Pagination.Next).ToString()"}' -UseBasicParsing
想请教如何在PowerShell中正确提取该格式的字符串?
解决方案
错误原因
你当前的写法是把PowerShell代码直接硬写到了JSON字符串里,API收到的不是实际的Base64分页值,而是一段代码文本,自然会解析失败。正确的做法是先解析首次响应的JSON,提取出next值,再将其代入后续请求的JSON Body中。
正确实现步骤
- 发起首次请求,提取分页Token
# 首次请求(根据接口要求,不带next参数或传空值) $firstResponse = Invoke-WebRequest -Uri 'https://cloud.apiiuse.com/api/v3/assets/' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"limit":1000}' -UseBasicParsing # 解析响应为JSON对象 $firstJson = $firstResponse.Content | ConvertFrom-Json # 提取分页的next值 $nextPageToken = $firstJson.pagination.next
- 构造后续请求的Body
有两种可靠的方式:
方式1:Here-String拼接JSON
# 用双引号Here-String让PowerShell自动解析变量 $body = @" {"limit":1000,"next":"$nextPageToken"} "@ # 发起后续请求 $response = Invoke-WebRequest -Uri 'https://cloud.apiiuse.com/api/v3/assets/' -Method POST -Headers $headers -ContentType 'application/json' -Body $body -UseBasicParsing
方式2:用ConvertTo-Json生成JSON(推荐)
如果next值包含特殊字符(如引号),手动拼接容易出错,用ConvertTo-Json会自动处理转义:
# 构造请求参数对象 $requestParams = @{ limit = 1000 next = $nextPageToken } # 转换为标准JSON格式 $body = $requestParams | ConvertTo-Json # 发起请求 $response = Invoke-WebRequest -Uri 'https://cloud.apiiuse.com/api/v3/assets/' -Method POST -Headers $headers -ContentType 'application/json' -Body $body -UseBasicParsing
内容的提问来源于stack exchange,提问作者JohnW

