PowerShell调用丹麦StatBank API遇REQUEST-EMPTY错误求助
PowerShell调用丹麦StatBank API时触发REQUEST-EMPTY错误的排查与修复
错误信息
Error calling the API: "errorTypeCode":"REQUEST-EMPTY","message":"Supply valid JSON-object when posting.".Exception.Message"
问题背景
调用丹麦StatBank API时出现上述错误,第一个脚本可正常运行,第二个脚本执行失败,无法定位语法差异。
正常运行的脚本
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $apiUrl = "https://api.statbank.dk/v1/data" $payload = @{ "table" = "FOLK1c" "format" = "CSV" "variables" = @( @{ "code" = "IELAND" "values" = @("5100","0000") } ) } try { $response = Invoke-RestMethod -Uri $apiUrl -Headers @{ "Content-Type" = "application/json" } -Method Post -Body ($payload | ConvertTo-Json) if ($response) { # Store CSV data in a variable $csvData = $response $filePath = "C:\" $csvData | Out-File -FilePath $filePath -Encoding UTF8 Write-Host "CSV data has been saved to: $filePath" } else { Write-Host "API returned no data." } } catch { Write-Host "Error calling the API: $_.Exception.Message" }
运行失败的脚本
\[Net.ServicePointManager\]::SecurityProtocol = \[Net.SecurityProtocolType\]::Tls12 $apiUrl = "https://api.statbank.dk/v1/data" $payload = @{ "table" = "AUS08" "format" = "CSV" "variables" = @( @{ "code" = "OMRÅDE" "values" = @("*") }, @{ "code" = "SAESONFAK" "values" = @("*") }, @{ "code" = "Tid" "values" = @("\*") } ) } | ConvertTo-Json try { $response = Invoke-WebRequest -Uri $apiUrl -Headers @{ "Content-Type" = "application/json" } -Method Post -Body $payload if ($response) { $csvData = $response.Content $filePath = "C:\" $csvData | Out-File -FilePath $filePath -Encoding UTF8 Write-Host "CSV data has been saved to: $filePath" } else { Write-Host "API returned no data." } } catch { Write-Host "Error calling the API: $\_.Exception.Message" }
错误原因分析
失败脚本存在3处不必要的反斜杠转义,导致代码解析异常:
\[Net.ServicePointManager\]和\[Net.SecurityProtocolType\]中的反斜杠,会让PowerShell无法识别这些.NET类型,后续逻辑执行异常。values数组中的@("\*")多了反斜杠,星号被转义成普通字符,既不符合API对通配符的要求,也会导致JSON格式错误。- 异常捕获中的
$\_.Exception.Message多了反斜杠,无法正确获取异常信息。
这些问题最终导致发送给API的JSON不符合要求,触发"REQUEST-EMPTY"错误。
修复后的脚本
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $apiUrl = "https://api.statbank.dk/v1/data" $payload = @{ "table" = "AUS08" "format" = "CSV" "variables" = @( @{ "code" = "OMRÅDE" "values" = @("*") }, @{ "code" = "SAESONFAK" "values" = @("*") }, @{ "code" = "Tid" "values" = @("*") } ) } | ConvertTo-Json try { $response = Invoke-WebRequest -Uri $apiUrl -Headers @{ "Content-Type" = "application/json" } -Method Post -Body $payload if ($response) { $csvData = $response.Content $filePath = "C:\" $csvData | Out-File -FilePath $filePath -Encoding UTF8 Write-Host "CSV data has been saved to: $filePath" } else { Write-Host "API returned no data." } } catch { Write-Host "Error calling the API: $_.Exception.Message" }
内容的提问来源于stack exchange,提问作者Staffyeahh
相关产品推荐
相关产品推荐

