且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法使用Powershell脚本调用包含multipart/form-data的HTTP POST

更新时间:2022-05-18 08:03:23

在这种情况下,400可能表示生成

In this scenario, the 400 probably means something was incorrect in generating the

文件是您需要提交的唯一参数吗?如果是这样,您也许可以使用WebClient.UploadFile API并让其处理生成大量请求.

Is the file the only parameter you need to submit on the request? If so, you may be able to use the WebClient.UploadFile API and let it handle generating the bulk of the request.

$client = New-Object System.Net.WebClient
$client.Credentials = $creds
$client.UploadFile('http://localhost/rest/backups', 'c:\temp\somefile.sql.gz')

如果您确实需要在mime multipart请求中提交多个参数,那么您将面临很多麻烦.我必须自己通过Powershell来执行此操作,这一点都不好玩,尤其是当您开始涉及二进制数据时.经过许多挫败感爆炸,我最终得到以下结果来转换值的哈希表并输出一个多部分.抱歉,我无法确切发现您的代码出了什么问题,但这也许可以完全为您解决,也可以使您确定问题所在.

If you do need to submit multiple parameters in a mime multipart request, then you're looking at a world of pain. I've had to do this through powershell myself and it's not fun at all, particularly when you start involving binary data. After much frustration & headbanging, I ended up with the following to convert a hashtable of values and outputs a multipart. Sorry I can't spot exactly what's wrong with your code, but perhaps this can will either work outright for you, or lead you to identify what your issue is.

function ConvertTo-MimeMultiPartBody
{
    param(
        [Parameter(Mandatory=$true)]
        [string]$Boundary,
        [Parameter(Mandatory=$true)]
        [hashtable]$Data
    )

    $body = '';

    $Data.GetEnumerator() |% {
        $name = $_.Key
        $value = $_.Value

        $body += "--$Boundary`r`n"
        $body += "Content-Disposition: form-data; name=`"$name`""
        if ($value -is [byte[]]) {
            $fileName = $Data['FileName']
            if(!$fileName) {
                $fileName = $name
            }
            $body += "; filename=`"$fileName`"`r`n"
            $body += 'Content-Type: application/octet-stream'
            #ISO-8859-1 is only encoding where byte value == code point value
            $value = [System.Text.Encoding]::GetEncoding("ISO-8859-1").GetString($value)
        }
        $body += "`r`n`r`n"
        $body += $value
        $body += "`r`n"
    }
    $body += "--$boundary--"
    return $body
}