Laravel HTTP客户端缺少body参数

问题描述 投票:0回答:1

我试着把我内部的Guzzle客户端切换到Laravel的新HTTP客户端。但不幸的是, 我没有收到相同的响应. 我也试过用HTTP asForm请求发送参数, 但是收到一个严重的错误.

有什么办法吗? 问候, Stan

口令要求

            $body = 'grant_type=authorization_code&code=' . $request->code . '&redirect_uri=' . urlencode($redirect_url);


            $client = new Client();

            $response = $client->post($endpoint, [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'auth' => [
                    $client_id,
                    $client_secret,
                ],
                'body' => $body,
            ]);

Http请求

       $response = Http::withHeaders([
            'Content-Type' => 'application/x-www-form-urlencoded'
        ])->
        withBasicAuth($client_id, $client_secret)
        ->post($token_endpoint,
                [
                    'grant_type' => 'authorization_code',
                    'code' => $request->code,
                    'redirect_uri' => urlencode($redirect_url)
                ]);

**错误

enter image description here

php laravel guzzle
1个回答
0
投票

Laravel的HTTP客户端不尊重你的内容头.

这是我的请求:

Http::withHeaders([
    'Content-Type' => 'application/x-www-form-urlencoded',
])
    ->withBasicAuth('user', 'pass')
    ->withoutVerifying()
    ->post('test-app.test', [
        'grant_type' => 'authorization_code',
        'code' => 'asdf',
        'redirect_uri' => 'asdf',
    ]);

这是我的应用程序收到的正文。

"{"grant_type":"authorization_code","code":"asdf","redirect_uri":"asdf"}"

你可能是混淆了OAuth服务器的视线 你告诉它你发送了 application/x-www-form-urlencoded 当你真正发出 application/json.

尝试更新你的代码以使用正确的内容类型。


Http::withHeaders([
    'Content-Type' => 'application/json',
])
//

0
投票

去掉自定义的Header类型并使用asForm()可以解决这个问题。

$response = Http::withBasicAuth($client, $client_secret)
            ->asForm()->post($endpoint,
                [
                    'grant_type' => 'authorization_code',
                    'code' => $request->code,
                    'redirect_uri' => $redirect_url
                ]);

https:/laravel.comdocs7.xhttp-client#request-data。

© www.soinside.com 2019 - 2024. All rights reserved.