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

标签 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 应用程序中使用相同的数据运行相同的 url 时,我得到了正确的结果:

enter image description here

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

如何解决我的问题?

最佳答案

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

关于laravel - Guzzle - Laravel。如何使用 x-www-form-url-encoded 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49681530/

相关文章:

laravel - 我不能使用 HHVM/Laravel 运行什么?

date - 如何配置我的 Postman 模拟服务器响应以始终返回过去两天的日期?

php - 如何使用 Guzzle 执行并发 POST 请求?

php - 测试监听 webhook 的 Laravel 路由

php - 将数据从集合回显到 Blade View

php - 如何在 Laravel 5 中更新用户密码?

php - Composer 不自动加载包

php - Laravel:将任意 URL 解析为其相应的 Controller /路由?

javascript - Postman 条件测试 json 主体数组是否为空 = 跳过测试

node.js - 当调用post方法时,当密码对应时,它会进入if语句,但我的if语句中的res被忽略,为什么?