1

使用 Postman,API 调用有效。我使用他们的代码片段功能来获得 PowerShell 等效项。但是当我在 PowerShell ISE 上尝试时,我得到“不允许空请求正文”。为什么它认为身体是空的?如何确认/查看 $body 的内容?

using assembly System.Net.Http
using namespace System.Net.Http

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer token")

$multipartContent = [System.Net.Http.MultipartFormDataContent]::new()

$multipartFile = 'C:\Users\xxx\Desktop\msg.json'
$FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open)
$fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
$fileHeader.Name = "ParameterRequest"
$fileContent = [System.Net.Http.StreamContent]::new($FileStream)
$fileContent.Headers.ContentDisposition = $fileHeader
$multipartContent.Add($fileContent)
$FileStream.Flush()
$FileStream.Close()

$multipartFile = 'C:\Users\xxx\Desktop\edm_payload'
$FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open)
$fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
$fileHeader.Name = "MessagePayload"
$fileContent = [System.Net.Http.StreamContent]::new($FileStream)
$fileContent.Headers.ContentDisposition = $fileHeader
$multipartContent.Add($fileContent)
$FileStream.Flush()
$FileStream.Close()

$body = $multipartContent

$response = Invoke-RestMethod -Method Post -Uri 'https://APIsite' -Headers $headers -Body $body -ContentType "multipart/form-data"

当我查看内容时,$body这就是我得到的。如何查看每个内容中的数据?

PS C:\Users\user> $body

Headers                                 
-------                                 
{[Content-Disposition, System.String[]]}
{[Content-Disposition, System.String[]]}

添加-VerboseInvoke-RestMethod我看到

VERBOSE: POST https://APIsite with -1-byte payload

我找不到“-1 字节有效负载”的含义。有人知道吗?

4

1 回答 1

0

解决了。部分问题是我使用的是 PowerShell v5,MultipartFormDataContent从那以后它得到了改进。更新到 PowerShell 的第 7 版,进行了一些调整……成功!

$formContent = New-Object -TypeName 'System.Net.Http.MultipartFormDataContent'

$filePath = "C:\Users\xxx\Desktop\msg.json"
$fileStream1 = [System.IO.File]::Open($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$formContent.Add([System.Net.Http.StreamContent]::new($fileStream1), "ParameterRequest", (Split-Path $filePath -leaf))

$filePath = "C:\Users\xxx\Desktop\edm_payload"
$fileStream2 = [System.IO.File]::Open($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$formContent.Add([System.Net.Http.StreamContent]::new($fileStream2), "MessagePayload", (Split-Path $filePath -leaf))

Invoke-RestMethod -Method Post -Uri 'https://APIsite' -Headers $requestHeader -Body $formContent -ContentType 'multipart/form-data'

另外 -在 API 调用关闭您的流

于 2021-02-17T18:52:56.353 回答