如何通过Powershell发出包含文件内容的POST请求

iqxoj9l9  于 2023-01-30  发布在  Shell
关注(0)|答案(1)|浏览(487)

我想用powershell进行一个post调用,它应该包含文件内容作为body,所以我尝试使用Invoke-Webrequest。当我这样进行调用时,服务器端没有数据。我可以看到在HttpServletRequest.getInputStream为null的服务器上,您知道问题是什么吗?

$FilePath = '.\foobar.txt'

$fileContent = Get-Content -Path $FilePath -Encoding Byte
Write-host $fileContent
$Response = Invoke-WebRequest -Body $fileContent -Method 'POST' -Uri 'http://myAddress'
xwbd5t1u

xwbd5t1u1#

tldr:需要添加参数-ContentType "application/octet-stream"
首先,你应该用[System.IO.File]::ReadAllBytes($FilePath)替换Get-Content -Path $FilePath -Encoding Byte,因为它更快。这也是为什么我不建议使用-InFile参数的原因,因为它内部也使用了缓慢,低性能的Get-Content方法。
在组合中,您可能还需要添加-ContentType "application/octet-stream",否则Body不会序列化为原始字节数组。
所以最后它应该看起来像这样:

$FilePath = '.\foobar.txt'
$fileContent = [System.IO.File]::ReadAllBytes($FilePath)
$Response = Invoke-WebRequest -Body $fileContent -Method 'POST' -Uri 'http://myAddress' -ContentType 'application/octet-stream'

相关问题