2017-06-22 730 views
0

我是新来的Guzzle,我试图做一个REST请求来签署PDF文件。该供应商说:guzzle,如何强制multipart/form-data中的内容类型

  • 您需要使用基本身份验证
  • 请求必须是POST请求
  • 的MIME类型应该是多部分/格式数据
  • 发送必须是文件的应用程序/ octet-流和它的名字应该是“文件”
  • 发送的数据必须是application/JSON和它的名字应该是“数据”

系统返回AR其中包含签名的PDF文件和类型是应用程序/八位字节流

这是我用Guzzle测试的代码,但提供者说应用程序/ pdf中发送了类型MIME。我怎样才能“强制”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()); 
    } 
} 

谢谢你的帮忙。

回答

0

您必须通过在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 Documentation

说,你可以为每个多数据指定头。 如果你没有设置标题Guzzle根据文件为你添加一个Content-Type。