PowerShell发送Multipart请求报400 Bad Request问题排查
问题根因
请求返回400是以下几个错误共同导致的:
- 接口明确要求请求格式为
multipart/form-data,但脚本将整个请求体序列化为JSON,指定application/json作为Content-Type,和接口要求的格式完全不符 - 错误套用curl命令的
@文件路径语法,PowerShell的Invoke-WebRequest不识别该写法,无法正确上传文件 appInfoJson字段被包裹在数组构造符@()中,接口要求该字段为单个JSON对象,不是数组结构- 所有布尔值、数字类型参数都被写成了带引号的字符串,和接口要求的参数类型不匹配
- 字段名写为
autoStart,和接口要求的autostart命名不一致,触发无效参数名错误
正确PowerShell实现代码
# 请求头配置 注意不要手动添加multipart/form-data的Content-Type,Invoke-WebRequest会自动生成带合法boundary的请求头 $Header = @{ 'X-ANYPNT-ENV-ID' = '4a96af5237cf1b64' 'X-ANYPNT-ORG-ID' = 'c6583b9fd79234ad' 'Authorization' = 'Bearer a2b6e09a-5e033d4c46c' } # 构造appInfo对象,严格匹配参数类型:布尔值传$true/$false,数字直接传数值,不要统一包成字符串 $appInfo = @{ "domain" = "testfi-fi-v1-proxy-test" "muleVersion" = @{"version" = "4.4.0"} "properties" = @{ "anypoint.platform.client_id" = "8f95f0f5c6b6" "secure.key" = "sYf%NslNRH*D$@" "env" = "dev" "anypoint.platform.client_secret" = "acF0D364be7a" } "propertiesOptions" = @{ "secure.key" = @{"secure" = $true } "anypoint.platform.client_secret"= @{"secure" = $true } } "region" = "us-west-1" "monitoringEnabled" = $true "monitoringAutoRestart" = $true "workers" = @{ "amount" = 1 "type" = @{ "name" = "Micro" "weight" = 0.1 "cpu" = "0.1 vCores" "memory" = "500 MB memory" } } "loggingNgEnabled" = $true "persistentQueues" = $true } # 将appInfo序列化为JSON字符串,作为表单的普通字段提交,Depth设为足够大的值避免层级截断 $appInfoJson = $appInfo | ConvertTo-Json -Depth 10 -Compress # 构造multipart/form-data表单 $Form = @{ file = Get-Item -Path "E:/actions-runner/workspace/target/sapi-ecm-documents-v1-1.0.2.jar" autostart = "true" appInfoJson = $appInfoJson } try { $result = Invoke-WebRequest -Method Post -Uri "https://anypoint.mulesoft.com/cloudhub/api/v2/applications" -Headers $Header -Form $Form # 接口返回内容为JSON字符串,需要先反序列化为对象才能读取属性 $respObj = $result.Content | ConvertFrom-Json Write-Output $respObj.domain Write-Output $respObj.muleVersion Write-Output $respObj.properties } catch { Write-Output '### 请求异常 ###' $ErrorMessage = $_.Exception.Message Write-Output "错误信息:$ErrorMessage" if ($_.Exception.Response) { $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $responseBody = $reader.ReadToEnd() Write-Output "接口返回详情:$responseBody" } }
注意事项
- 不要手动给请求添加
multipart/form-data类型的Content-Type头,手动添加会缺少boundary参数直接导致请求失效 - 如果实际接口文档中
autostart字段为驼峰命名autoStart,对应修改表单中的键名即可,需严格匹配接口要求的字段大小写 - 上传文件直接通过
Get-Item获取本地文件对象传给表单字段即可,不需要手动读取文件流 - PowerShell 5.1及以上版本原生支持
-Form参数处理multipart表单,目前主流Windows环境默认搭载的PowerShell版本均满足要求
内容的提问来源于stack exchange,提问作者wehelpdox
相关产品推荐
相关产品推荐

