食尸鬼-Laravel 如何使用x-www-form-url-encoded发出请求

Ale*_*Per 5 laravel guzzle postman 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]);

    }

}
Run Code Online (Sandbox Code Playgroud)

作为回应,我收到消息:

{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

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

如何解决我的问题?

Dyl*_*rce 8

问题在于,在Postman中,您是以表格形式发送数据,而在Guzzle中,您是'json'在options数组的键中传递数据。

我敢打赌,如果您将切换'json''form_params',则会得到想要的结果。

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

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

另外,我注意到有错字-您有cliend_id而不是client_id

  • 只是为了干净的代码:您可以使用“RequestOptions::FORM_PARAMS”常量,而不是自己将数组键写入字符串中。 (3认同)

Had*_*azi 5

如果您使用 Http 客户端,请尝试以表单形式asForm传递数据的方法x-www-form-url-encoded

精确的语法

Http::asForm()->post('demo.com');
Run Code Online (Sandbox Code Playgroud)