【发布时间】:2019-04-26 06:43:31
【问题描述】:
我正在尝试使用 Invoke-WebRequest 上传 XML 文件(不建议使用 Invoke-RestMethod 吗?)但是当尝试在标头中设置内容长度时,我收到错误:
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
【问题讨论】:
-
不应该是
"content-length" = 2182,数字两边不加引号吗? -
好收获!更改了它但仍然得到相同的错误:(在代码中更新。
-
Content-Length需要我认为的字节数,所以您的值 2182 可能与$xml的 byte 长度不匹配?试试"Content-Length" = [System.Text.Encoding]::ASCII.GetByteCount($xml)或"Content-Length" = [System.Text.Encoding]::UTF8.GetByteCount($xml) -
不错!我试过这个,它确实让我更接近于找出问题所在——结果是设置 Transfer-Encoding = chunked.将对此发布答案。
标签: powershell