Guzzle,如何强制在multipart/form-data中设置Content-Type?

3
我刚接触Guzzle,想尝试使用REST请求来签署PDF文件。供应商说:
  • 您需要使用BASIC身份验证
  • 请求必须是POST请求
  • mime类型应为multipart/form-data
  • 发送的文件必须是application/octet-stream类型,名称应为“file”
  • 发送的数据必须是application/json类型,名称应为“data”
系统返回一个响应,其中包含已签署的PDF文件,类型为application/octet-stream
这是我使用Guzzle测试的代码,但供应商说发送的mime类型是application/pdf。我该如何“强制”PDF文件的mime类型?
$client = new Client([
    'auth' => ['login', 'password'],
    'debug' => true,
    'curl'  => [
                  CURLOPT_PROXY => '192.168.1.232',
                  CURLOPT_PROXYPORT => '8080',
                  CURLOPT_PROXYUSERPWD => 'username:password',
             ],
]);
$boundary = 'my_custom_boundary';
$multipart = [
            [
                'name'     => 'data',
                'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
                'Content-Type'  => 'application/json'
            ],
            [
                'name'     => 'file',
                'contents' => fopen('documentTest.pdf', 'r'),
                'Content-Type'  => 'application/octet-stream'
            ],
        ];

$params = [
    'headers' => [
        'Connection' => 'close',
        'Content-Type' => 'multipart/form-data; boundary='.$boundary,
    ],
    'body' => new GuzzleHttp\Psr7\MultipartStream($multipart, $boundary),
];

try{
    $response = $client->request('POST', 'https://server.com/api/sendDocument', $params);
} catch (RequestException $e) {
    echo Psr7\str($e->getRequest());
    if ($e->hasResponse()) {
        echo Psr7\str($e->getResponse());
    }
}

感谢您的帮助。
1个回答

2
您需要在标头中传递Content-Type。
$multipart = [
        [
            'name'     => 'data',
            'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
            'headers'  => [ 'Content-Type' => 'application/json']
        ],
        [
            'name'     => 'file',
            'contents' => fopen('documentTest.pdf', 'r'),
            'headers'  => [ 'Content-Type' => 'application/octet-stream']
        ],
    ];

Guzzle文档中提到,您可以为每个多部分数据指定标头。如果您没有设置标头,Guzzle会根据文件为您设置Content-Type。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接