[英]file_get_contents(): Content-type not specified assuming 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());
有關更多詳細信息,請參閱文檔
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.