为什么我的授权标头在Guzzle中给我401?

Ali*_*ani 3 php guzzle

我在Guzzle 4.2上收到401,并且在Postman上也可以使用相同的设置。下面的代码。

// Create a client with a base URL
    $client = new GuzzleHttp\Client(['base_url' => 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1']);

    // Send a request to https://github.com/notifications
    $response = $client->get();

    //Auth
   $response->addHeader('Authorization', "auth-code");


    //send
    $r = $response->send();

   dd($r->json());
Run Code Online (Sandbox Code Playgroud)

错误是:

GuzzleHttp \ Exception \ ClientException (401) 
Client error response [url] cloud.feedly.com/v3/streams/contents?streamId=user/user-id/global.all&count=1 [status code] 401 [reason phrase] Unauthorized
Run Code Online (Sandbox Code Playgroud)

Sha*_*aun 5

纵观文档页面按这一行:

$response = $client->get();
Run Code Online (Sandbox Code Playgroud)

它将发送一个没有授权的获取请求,因此返回401响应。

尝试以下方法

// Create a client with a base URL.
$client = new GuzzleHttp\Client();

$request = $client-> createRequest('GET', 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1');

$request->setHeader('Authorization', "auth-code");

// Send.
$response = $client->send($request);

dd($response->json());
Run Code Online (Sandbox Code Playgroud)

上面创建了一个请求,在其上设置了授权头。然后,一旦准备好,它实际上将其发送。

我认为它在Postman中起作用,因为您的标头已设置,如果删除授权标头,它也很可能会失败。

我尚未对此进行测试,但认为它将起作用。