GuzzleHttp - 400错误异常,但卷曲工作完美

时间:2017-11-03 05:40:16

标签: guzzle guzzle6 guzzlehttp

我正在使用GuzzleHttp调用第三方休息API但每次都给我一个 400 Bad Request

  

开发环境

  1. laravel / php framework
  2. composer.json文件中的guzzle版本 - “guzzlehttp / guzzle”:“^ 6.3”
  3. Ubantu 16.04 LTS
  4.   

    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;
    
        }
    
      

    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,它工作得很完美并且得到了结果。

      

    包含网址和数据的卷曲代码

    $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;
    

    任何人都可以帮我弄清楚发生了什么事以及我做错了什么。

1 个答案:

答案 0 :(得分:1)

你需要

'json' => $body

而不是

'form_params' => $body