簡體   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