首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >内容长度和Invoke-WebRequest

内容长度和Invoke-WebRequest
EN

Stack Overflow用户
提问于 2019-04-25 08:41:33
回答 1查看 4.2K关注 0票数 0

我正在尝试使用Invoke-WebRequest上传XML文件(不推荐使用Invoke-RestMethod?)但在尝试设置头部中的content-length时,我得到了错误:

代码语言:javascript
复制
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,但似乎不能回答这个问题。

代码语言:javascript
复制
$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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-26 06:43:31

在尝试了@Theo的注释之后,我在头文件中添加了Transfer-Encoding,它看起来很有效!完整修复代码:

代码语言:javascript
复制
$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

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55840322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档