【问题标题】:Guzzle - Laravel. How to make request with x-www-form-url-encodedGuzzle - Laravel。如何使用 x-www-form-url-encoded 发出请求
【发布时间】:2018-09-15 19:36:51
【问题描述】:

我需要集成一个 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 时,我会得到正确的结果:

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

如何解决我的问题?

【问题讨论】:

    标签: laravel postman guzzle


    【解决方案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

    【讨论】:

    • client-Id 是个问题... 很多
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2018-12-25
    相关资源
    最近更新 更多