Guzzle - Laravel. How to make request with x-www-form-url-encoded

坚强是说给别人听的谎言 提交于 2019-12-06 03:49:50

问题


I need to integrate an API so I write function:

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]);

    }

}

as a responde I got message:

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

Now when I try to run the same url with same data in POSTMAN app then I get correct results:

What is bad in my code? I send correct form_params also I try to change form_params to json but again I got the same error...

How to solve my problem?


回答1:


The problem is that in Postman you're sending the data as a form, but in Guzzle you're passing the data in the 'json' key of the options array.

I bet that if you would switch the 'json' to 'form_params' you would get the result you're looking for.

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

Here's a link to the docs in question: http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields

Also, I noticed a typo - you have cliend_id instead of client_id.



来源:https://stackoverflow.com/questions/49681530/guzzle-laravel-how-to-make-request-with-x-www-form-url-encoded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!