【问题标题】:Content Length and Invoke-WebRequest内容长度和 Invoke-WebRequest
【发布时间】: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 可能与 $xmlbyte 长度不匹配?试试"Content-Length" = [System.Text.Encoding]::ASCII.GetByteCount($xml)"Content-Length" = [System.Text.Encoding]::UTF8.GetByteCount($xml)
  • 不错!我试过这个,它确实让我更接近于找出问题所在——结果是设置 Transfer-Encoding = chunked.将对此发布答案。

标签: powershell


【解决方案1】:

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

}

【讨论】:

  • 这对我不起作用。我得到 Invoke-RestMethod :必须使用适当的属性或方法修改“Transfer-Encoding”标头。在 powershell 3.0 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多