[英]Why do I get 403 Forbidden with Guzzle?
如果我使用 curl 進行響應,則 API 有效:
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => config('healy.loginServerHost') . '/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type=refresh_token&refresh_token=mytoken&app_version=1.0',
CURLOPT_USERPWD => config('healy.loginServerUsername') . ':' . config('healy.loginServerPassword'),
]);
$response = curl_exec($curl);
我得到了 200 個響應。 但是,當我嘗試將其與 GuzzleClient 6 一起使用時,我得到 403 Forbidden 響應。
$client = new GuzzleHttp\Client();
$response = $client->post(config('healy.loginServerHost') . '/token', [
'form_params' => [
'grand_type' => 'refresh_token',
'refresh_token' => 'mytoken',
'app_version' => 1.0,
],
'http_errors' => false,
'auth' => [
config('healy.loginServerUsername'),
config('healy.loginServerPassword'),
],
'options' => [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
],
]);
我在 Guzzle 中缺少什么? 這些電話不完全相同嗎?
沒有options
request_option,我們在使用 class GuzzleHttp\Handler\CurlMultiHandler
時使用帶有異步請求的選項。 請改用curl
request_option。
$client = new Client([
'curl' => [
\CURLOPT_ENCODING => '',
\CURLOPT_RETURNTRANSFER => true,
\CURLOPT_MAXREDIRS => 10,
\CURLOPT_TIMEOUT => 0,
\CURLOPT_FOLLOWLOCATION => true,
\CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
]
]);
$response = $client->post(config('healy.loginServerHost') . '/token', [
'form_params' => [
'grand_type' => 'refresh_token',
'refresh_token' => 'mytoken',
'app_version' => 1.0,
],
'http_errors' => false,
'auth' => [
config('healy.loginServerUsername'),
config('healy.loginServerPassword'),
]
]);
您也可以在請求中使用 curl 請求選項,作為選項數組的第三個參數。
但我建議如果您使用的是 guzzle,那么您應該完全使用它。 因此,您可以用 guzzle 提供的許多請求選項替換 curl 選項。
$client = new GuzzleHttp\Client(['curl' => [\CURLOPT_ENCODING => '', CURLOPT_RETURNTRANSFER => true]]);
$response = $client->post(config('healy.loginServerHost') . '/token', [
'form_params' => [
'grand_type' => 'refresh_token',
'refresh_token' => 'mytoken',
'app_version' => 1.0,
],
'http_errors' => false,
'auth' => [
config('healy.loginServerUsername'),
config('healy.loginServerPassword'),
],
'allow_redirects' => [
'max' => 10, // allow at most 10 redirects.
'strict' => true, // use "strict" RFC compliant redirects.
// 'referer' => true, // add a Referer header
'protocols' => ['https'], // only allow https URLs
// 'on_redirect' => $onRedirect,
'track_redirects' => true
],
'version' => 1.1 // equivalent to CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
// No need of \CURLOPT_TIMEOUT => 0, as it is by default 0, if want any other value then use timeout request options
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.