Laravel用Guzzle调用AmadeusAPI表单提交返回JSON无法解析,Postman正常
错误根因
- 参数配置冲突:Guzzle的
form_params参数用于发送application/x-www-form-urlencoded格式的表单数据,和你设置的Content-Type: application/json请求头完全不匹配,发送JSON请求需要使用json配置项。 - 参数格式错误:表单提交的
datas是JSON字符串,你直接将字符串赋值给flightOffers字段,未解码为数组,导致最终请求体结构不符合接口要求。 - 代码逻辑错误:请求成功后你已经读取了响应体内容,后续调用
$res->getResponse()属于无效调用,且代码中$items变量未定义会触发额外报错。
修复方案
直接替换控制器代码如下:
public function comparePrices(Request $request) { // 简化获取token的写法,无需全表查询再取值 $token = DB::table('a_p_is_tokens') ->orderBy('id', 'desc') ->value('token'); $client = new Client(); try { // 先解码表单传入的JSON字符串为数组 $flightOffers = json_decode($request->input('datas'), true); // 提前校验传入的JSON是否合法 if (json_last_error() !== JSON_ERROR_NONE) { return response()->json(['error' => 'datas参数不是合法的JSON格式'], 400); } $res = $client->post('https://test.api.amadeus.com/v1/shopping/flight-offers/pricing', [ 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $token, ], // 用json配置项自动序列化数组为JSON,自动生成正确的Content-Type头 'json' => [ "data" => [ "type" => "flight-offers-pricing", "flightOffers" => $flightOffers, ], ] ]); $result = json_decode($res->getBody()->getContents(), true); print_r($result); // return view('agents.agentsTickets'); } catch (RequestException $e) { $response = $e->getResponse(); $result = json_decode($response->getBody()->getContents()); return response()->json(['data' => $result]); } return view('agents.agentsTickets'); }
验证建议
- 发送请求前可以打印
json_encode($request->datas)和Postman的请求体做对比,确保结构完全一致。 - 确认视图层输入框提交的
datas是合法JSON格式,避免传入特殊字符或格式错误的字符串。
内容的提问来源于stack exchange,提问作者ERaufi
相关产品推荐
相关产品推荐

