狂饮 - Laravel。如何使用 x-www-form-url-encoded 发出请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49681530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:36:19  来源:igfitidea点击:

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

laravelpostmanguzzleguzzlehttp

提问by Aleks Per

I need to integrate an API so I write function:

我需要集成一个 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]);

    }

}

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:

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

enter image description here

在此处输入图片说明

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

我的代码有什么不好?我form_params也发送正确我尝试将 form_params 更改为 json 但我再次遇到相同的错误...

How to solve my problem?

如何解决我的问题?

回答by Dylan Pierce

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.

问题在于,在 Postman 中,您将数据作为表单发送,但在 Guzzle 中,您将数据传递'json'到 options 数组的键中。

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

我敢打赌,如果你切换'json''form_params'你会得到你正在寻找的结果。

$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

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

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

另外,我注意到一个错字 - 你有cliend_id而不是client_id.