内容长度和调用WebRequest

时间:2019-04-25 00:41:33

标签: powershell

我尝试使用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

1 个答案:

答案 0 :(得分:0)

尝试@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

}