鍍金池/ 問答/PHP  網(wǎng)絡(luò)安全/ 關(guān)于guzzle表單本地文件上傳的問題

關(guān)于guzzle表單本地文件上傳的問題

請教各位一個(gè)問題。
最近在調(diào)試一個(gè)第三方的api,然后使用了guzzle做客戶端,其中該api的一個(gè)請求參數(shù)需要使用本地圖片的二進(jìn)制數(shù)據(jù),我翻了下guzzle的手冊,然后查找了下文檔http://guzzle-cn.readthedocs....,按照這上面的試了下,服務(wù)端一直提示說我的的請求解析出錯(cuò),要我檢查下content-type and body,試了很久也沒解決,希望有熟悉的大神提點(diǎn)下,謝謝了。代碼如下

$client  = new Client();
         $instance = sign::getInstance();
         $url = 'http://XXXXX';
         $sign = $instance->getSign();
        
         //hearder頭
         $header = ['Host'=>'XXXXXXX','Content-Type'=>'multipart/form-data','Authorization'=>$sign];
         //本地圖片
         $file = file_get_contents('D:\wamp64\www\whistles-master\test.jpg');
         //body
         $body = [
               [
                  'name'=>'appid',
                  'contents'=>'XXXX'
               ],
               [
                  'name'=>'bucket',
                  'contents'=>'XXXXX'
               ],
               [
                  'name'=>'type',
                  'contents'=> 0
               ],
               [
                   'name'=>'image',
                   'contents'=>fopen('D:\wamp64\www\whistles-master\test.jpg', 'r')
               ]
              
              
         ];

         $res = $client->request('POST',$url,          ['headers'=>$header,'multipart'=>$body]);

         echo  $res->getBody();

報(bào)錯(cuò)信息如下

GuzzleHttp\Exception\ClientException: Client error: `POST http://XXXXX` resulted in a `400 Bad Request` response: {"code":3,"message":"invalid request: parsing error - check content-type and body","data":{}} in D:\XXXXXXXXX\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113
回答
編輯回答
遲月
try {
    $response = $client->request('POST', '/face/detect', [
        'headers' => [
            'authorization' => $signStr,
        ],
        'multipart' => [
            [
                'name' => 'appid',
                'contents' => $appid,
            ],
            [
                'name' => 'mode',
                'contents' => 1,
            ],
            [
                'name' => 'image',
                'contents' => fopen('/home/chenyarong/Pictures/mayun/0.jpg', 'r'),
            ],
        ]
    ]);
} catch (\Exception $ex) {
    var_dump($ex->getMessage());exit;
}

echo $response->getBody();

我最近剛好也在用騰訊的人臉識別,也遇到這個(gè)問題,測試過程中,代碼好像跟你的沒有區(qū)別, 少了Host, 少了Content-Type 的設(shè)置,guzzle自己應(yīng)該條件了,然后測試沒問題,能夠正常的返回.

2017年10月21日 20:14