我正在尝试使用Invoke-WebRequest上传XML文件(不推荐使用Invoke-RestMethod?)但在尝试设置头部中的content-length时,我得到了错误:
Invoke-WebRequest : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.我需要创建一个请求流吗?我已经检查了https://social.technet.microsoft.com/Forums/windowsserver/en-US/d18f4ae9-4a5d-495f-aa2d-fbda3d616967/invokewebrequest-you-must-write-contentlength-bytes-to-the-request-stream-before-calling,但似乎不能回答这个问题。
$requestHeaders = @{
"content-length" = 2182
"Content-Type" = "application/xml"
"Authorization" = "Bearer " + $response.access_token
}
$body = @"
$xml
"@
$result = Invoke-WebRequest -Method Post -Uri "{uri}" -Headers $requestHeaders -Body $Body发布于 2019-04-26 06:43:31
在尝试了@Theo的注释之后,我在头文件中添加了Transfer-Encoding,它看起来很有效!完整修复代码:
$requestHeaders = @{
#content-length not needed?
"Transfer-Encoding" = "chunked"
"Content-Type" = "application/xml"
"Authorization" = "Bearer " + $response.access_token
}
try {
$result = Invoke-RestMethod -Method Post -Uri "{uri}" -Headers $requestHeaders -Body $xml
} catch {
# write exception message
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Host $responseBody
}https://stackoverflow.com/questions/55840322
复制相似问题