GuzzleHttp - 400 错误异常但 curl 工作正常

GuzzleHttp - 400 error exception but with curl working perfectly

我正在使用 GuzzleHttp 调用第三方 rest API,但它每次都会给我一个 400 Bad Request

开发环境:

  1. Laravel / PHP 框架
  2. Guzzle 版本在 composer.json 文件中 - "guzzlehttp/guzzle": "^6.3"
  3. Ubuntu 16.04 LTS

Guzzle 使用数据调用 URL:

try{

$client = new \GuzzleHttp\Client();

$res= $client->request('post',
            env('FLIGHT_API').'FlightSearch',
            ['headers' => ['Content-Type' => 'application/json' , 'Accept' => 'application/json'],'form_params' => $body]);

}catch (ClientException $e){



        $response['status'] = false;
        $response['message'] = $e->getMessage().$e->getCode();

        return $response;

    }

Guzzle 回复:

{
"status": false,
"message": "Client error: `POST http://stagingapi.trip.com/Search` resulted in a `400 Bad Request` response:\n\ufeff<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3 (truncated...)\n400"
}

所以,最后我用 curl 尝试了同样的 API,它运行完美并得到了结果。

带有 URL 和数据的卷曲代码:

$curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('FLIGHT_API').'FlightSearch',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/json",
                "Accept: application/json"
            ),
        ));

        $response = curl_exec($curl);
        //return $response;
        $err = curl_error($curl);

        curl_close($curl);

        if($response){

            return json_decode($response , true);

        }

        return $err;

如何判断问题出在哪里?

你需要

'json' => $body

而不是

'form_params' => $body