【发布时间】:2018-04-15 19:04:48
【问题描述】:
我正在使用 GuzzleHttp 调用第三方 rest API,但它每次都会给我一个 400 Bad Request。
开发环境:
- Laravel / PHP 框架
- composer.json 文件中的 Guzzle 版本 - “guzzlehttp/guzzle”:“^6.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;
如何确定故障在哪里?
【问题讨论】: