繁体   English   中英

如何通过在laravel中传递参数来获得内容类型application/x-www-form-urlencoded的响应

[英]How to get response of content type application/x-www-form-urlencoded by passing parameters in laravel

我已经在 Laravel https://sso/{custom_path}/token 中使用 Api 进行单点登录选项,就像使用 jwt 创建的这个 Api。 在我的 Web 应用程序中,使用 http 客户端 guzzle 将标头中的访问令牌和内容类型传递给 Api 调用。 内容类型为 application/x-www-form-urlencoded,参数为 form_params。 但作为回应,我丢失了grant_type。 当我在 form_parms 数组中传递 grant_type 时。 有没有其他方法可以解决这个问题。 任何有价值的回应都会被考虑。

代码:

$uri = $this->userTokenAuthencticateUrl();
        $token = session('token')->access_token;
        $params['header'] = [
            "Content-Type: application/x-www-form-urlencoded",
            "Authorization: Bearer $token"
            ];
        $params['form_params'] = array(
                'grant_type' => 'xxxxx',
                'response_include_resource_name' => 'xxx',
                'audience' => 'xxxx', 
                'permission' => 'xxxxxx',
            );
            $response = Http::post($uri, $params);
            dd($response->json());

回应:

array:2 [▼
  "error" => "invalid_request"
  "error_description" => "Missing form parameter: grant_type"
]

当您使用 HTTP 客户端时。 你需要改变你的代码。 您不需要在标题中将 Content-Type 作为application/x-www-form-urlencoded传递,我相信授权令牌是在标题中单独传递的,您可以将其传递到参数中。

$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;

 $params = array(
        'grant_type' => 'xxxxx',
        'response_include_resource_name' => 'xxx',
        'audience' => 'xxxx', 
        'permission' => 'xxxxxx',
 );
 $response = Http::asForm()->withHeaders([
        'Authorization' => 'Bearer ' . $token
     ])->post($uri, $params);

 dd($response->json());

方法二:

它也在文档中提到

如果您想快速向请求添加授权不记名令牌标头,您可以使用 withToken 方法,这样您也可以这样做

$uri = $this->userTokenAuthencticateUrl(); $token = session('token')->access_token; $params = array( 'grant_type' => 'xxxxx', 'response_include_resource_name' => 'xxx', 'audience' => 'xxxx', 'permission' => 'xxxxxx', ); $response = Http::asForm()->withToken($token)->post($uri, $params); dd($response->json());

有关更多详细信息,请参阅文档


方法三:

您甚至可以直接使用 guzzle。
 define("form_params", \\GuzzleHttp\\RequestOptions::FORM_PARAMS ); try{ $client = new \\GuzzleHttp\\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]); $guzzleResponse = $client->post( $api_url, [ 'form_params' => [ 'grant_type' => 'xxxxx', 'response_include_resource_name' => 'xxx', 'audience' => 'xxxx', 'permission' => 'xxxxxx' ] ]); if ($guzzleResponse->getStatusCode() == 200) { $response = json_decode($guzzleResponse->getBody(),true); //perform your action with $response } } catch(\\GuzzleHttp\\Exception\\RequestException $e){ // you can catch here 400 response errors and 500 response errors // see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600 }catch(Exception $e){ //other errors }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM