Laravel中Guzzle调用Amadeus API返回Bad Request错误如何解决
问题原因
- Authorization请求头格式错误:Guzzle的headers配置中,Authorization值需要是完整的
Bearer {token}字符串,你当前传入的是数组格式,会导致请求头格式不符合接口要求。 - GET请求参数配置错误:
form_params是Guzzle专门用于POST请求提交表单参数的配置项,GET请求的查询参数需要配置在query项中,你当前的请求参数根本没有被拼接在请求URL后,接口无法获取必要参数因此返回400错误。 - 异常捕获块逻辑错误:请求触发异常时
$res对象未完成赋值,无法直接调用getResponse()方法,需要从异常实例$e中获取响应对象。
修正后代码
public function agentsTicket(Request $request) { $client = new Client(); try { $res = $client->get('https://test.api.amadeus.com/v2/shopping/flight-offers', [ 'headers' => [ 'Authorization' => 'Bearer 123456789', ], 'query' => [ "originLocationCode" => "SYD", "destinationLocationCode" => "BKK", "departureDate" => "2021-11-01", "returnDate" => "2021-11-18", "adults" => "2", "max" => "1", ] ]); $res = json_decode($res->getBody()->getContents(), true); dd($res); } catch (\Exception $e) { $response = $e->getResponse(); $result = json_decode($response->getBody()->getContents()); return response()->json(['data' => $result]); } }
内容的提问来源于stack exchange,提问作者ERaufi
相关产品推荐
相关产品推荐

