【问题标题】:GuzzleHttp - 400 error exception but with curl working perfectlyGuzzleHttp - 400 错误异常,但 curl 工作正常
【发布时间】:2018-04-15 19:04:48
【问题描述】:

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

开发环境:

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

使用数据对 URL 进行 Guzzle 调用:

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;

    }

贪婪回应:

{
"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;

如何确定故障在哪里?

【问题讨论】:

    标签: guzzle6 guzzle


    【解决方案1】:

    你需要

    'json' => $body
    

    而不是

    'form_params' => $body
    

    【讨论】:

    • 这对我有用,但你能告诉我'fomr_params'和'json'有什么区别吗?在什么条件下可以使用哪一个?
    • 它是described in the docsforms_params 是发送 HTML 表单,json 是发送 JSON。
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多