为什么我的授权标头在Guzzle中给我401? [英] Why is my Authorization Header giving me a 401 in Guzzle?

查看:339
本文介绍了为什么我的授权标头在Guzzle中给我401?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Guzzle 4.2上得到了401,在Postman上也可以使用相同的设置.下面的代码.

I am getting a 401 on Guzzle 4.2 and the same setup works on Postman. Code below.

// 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());

错误是:

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

推荐答案

查看文档页面,如下所示:

$response = $client->get();

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

It will send a get request, with no authorisation, hence the 401 response.

请尝试以下操作

// 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());

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

The above creates a request, set the authorisation header on it. Then once prepared it actually sends it.

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

I think it worked in Postman because your headers are set, if you remove the authorization header it will likely fail there too.

我还没有测试过,但是认为它可以工作.

I have not tested this but think it will work.

这篇关于为什么我的授权标头在Guzzle中给我401?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆