Guzzle - Laravel。如何使用x-www-form-url-encoded进行请求

时间:2018-04-05 21:06:52

标签: laravel postman guzzle guzzlehttp

我需要集成一个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应用程序中运行相同数据的相同网址时,我得到了正确的结果:

enter image description here

我的代码有什么不好?我发送正确的form_params我也尝试将form_params更改为json,但我又得到了同样的错误......

如何解决我的问题?

1 个答案:

答案 0 :(得分:1)

问题在于,在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