Laravel中使用Guzzle发送x-www-form-urlencoded请求的问题
正确使用Guzzle发送x-www-form-urlencoded请求
嘿,我一眼就看到问题所在了——你虽然手动设置了x-www-form-urlencoded的Content-Type,但用错了参数来传递表单数据,这才导致请求异常!
问题根源
你代码里用了json参数来传递键值对,Guzzle会自动把这个参数里的数组转成JSON字符串,同时还会偷偷把请求头的Content-Type覆盖成application/json,这就和你手动设置的x-www-form-urlencoded完全冲突了,服务器自然无法正确解析你的请求。另外还要注意:你代码里的cliend_id是拼写错误,应该是client_id,这个小细节也很容易导致请求失败!
正确写法
发送x-www-form-urlencoded类型的请求时,应该使用form_params参数来传递表单数据,而不是json。下面是修正后的完整代码:
public function test() { $client = new GuzzleHttp\Client(); try { $res = $client->post('http://example.co.uk/auth/token', [ 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', ], 'form_params' => [ 'client_id' => 'SOMEID', // 修正拼写错误 'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=', 'grant_type' => 'client_credentials' ] ]); $res = json_decode($res->getBody()->getContents(), true); dd($res); } catch (GuzzleHttp\Exception\RequestException $e) { // 建议添加异常处理,方便排查问题 dd($e->getMessage(), $e->getResponse()?->getBody()->getContents()); } }
更简洁的写法
其实Guzzle在使用form_params参数时,会自动帮你设置Content-Type为application/x-www-form-urlencoded,所以你甚至可以省略手动设置的headers部分,代码会更干净:
public function test() { $client = new GuzzleHttp\Client(); try { $res = $client->post('http://example.co.uk/auth/token', [ 'form_params' => [ 'client_id' => 'SOMEID', 'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=', 'grant_type' => 'client_credentials' ] ]); $res = json_decode($res->getBody()->getContents(), true); dd($res); } catch (GuzzleHttp\Exception\RequestException $e) { dd($e->getMessage(), $e->getResponse()?->getBody()->getContents()); } }
内容的提问来源于stack exchange,提问作者Aleks Per
相关产品推荐
相关产品推荐

