Guzzle - Laravel. 如何使用x-www-form-url-encoded发送请求

27

我需要集成一个API,所以我编写了以下函数:

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',
            ],

    'json' => [
        'cliend_id' => 'SOMEID',
        'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
        'grant_type' => 'client_credentials'
]
            ]);

$res = json_decode($res->getBody()->getContents(), true);
dd($res);

}
catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $result =  json_decode($response->getBody()->getContents());

    return response()->json(['data' => $result]);

    }

}

作为响应,我收到了这条消息:

{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}

现在当我尝试使用POSTMAN应用程序以相同的数据运行相同的URL时,我会得到正确的结果:

enter image description here

我的代码有什么问题?我发送了正确的form_params ,也尝试将form_params更改为JSON,但仍然遇到相同的错误...

如何解决我的问题?

2个回答

54

问题在于在Postman中,您将数据发送为表单形式,但是在Guzzle中,您将数据传递给选项数组的'json'键。

我敢打赌,如果您将'json'切换为'form_params',您将得到您要查找的结果。

$res = $client->post('http://example.co.uk/auth/token', [
    'form_params' => [
        'client_id' => 'SOMEID',
        'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
        'grant_type' => 'client_credentials'
    ]
]);

以下是相关文档链接:http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields

另外,我发现有个拼写错误 - cliend_id 应该改为 client_id


1
cliend-Id是一个问题...这很多。 - Aleks Per
3
为了代码的整洁,您可以使用 RequestOptions::FORM_PARAMS 常量而不是自己编写字符串中的数组键。 - WhySoToxic
例如,您可以使用以下方式进行POST请求:$request->asForm()->post($url, $data); - ahmad-mohammadi

4
如果您正在使用 Http Client,请尝试使用 asForm 方法以 x-www-form-url-encoded 格式传递数据。
确切的语法。
Http::asForm()->post('demo.com');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接