duanqinqian5299
2016-03-15 12:48
浏览 440
已采纳

Guzzle HTTP - 将Authorization标头直接添加到请求中

Can anyone explain how to add the Authorization Header within Guzzle? I can see the code below works for adding the username & password but in my instance I just want to add the Authorization header itself

$client->request('GET', '/get', ['auth' => ['username', 'password']

The Basic Authorization header I want to add to my GET request :-

Basic aGdkZQ1vOjBmNmFmYzdhMjhiMjcwZmE4YjEwOTQwMjc2NGQ3NDgxM2JhMjJkZjZlM2JlMzU5MTVlNGRkMTVlMGJlMWFiYmI=
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongzhidian3538 2016-03-15 13:27
    已采纳

    From the looks of things, you are attempting to use an API key. To obtain your desired effect, simply pass null in as the username, like below.

    $client->request(
        $method,
        $url,
        [
            'auth' = [
                null,
                $api_key
            ],
        ]
    );
    
    已采纳该答案
    打赏 评论
  • dongpu6141 2016-03-15 14:01

    I don't know how I missed reading that you were looking for the Basic auth header, but nonetheless hope this helps somewhat. If you are just looking to add the Authorization header, that should be pretty easy.

    // Set various headers on a request
    $client->request('GET', '/get', [
    'headers' => [
        'Authorization'     => 'PUT WHATEVER YOU WANT HERE'
        ]
    ]);
    

    I build up my request in Guzzle piece by piece so I use the following:

    $client = new GuzzleHttp\Client();
    $request = $client->createRequest('GET', '/get');
    $request->addHeader('X-Authorization', 'OAuth realm=<OAUTH STUFF HERE>');
    $resp = $client->send($request);
    

    Hope that helps. Also, make sure to include the version of Libraries you are using in the future as syntax changes depending on your version.

    打赏 评论
  • dongsigan2636 2016-10-28 09:33
    use GuzzleHttp\Client;
    

    ...

    $client = new Client(['auth' => [$username, $password]]);
    $res = $client->request('GET', 'url', ['query' => ['param1'=>$p1, 'param2'=>'sometext']]);
    $res->getStatusCode();
    $response = $res->getBody();
    

    This creates an authorized client and sends a get request along with desired params

    打赏 评论
  • dongmaopan5738 2017-04-05 00:55

    I'm using Guzzle 6. If you want to use the Basic Auth Scheme:

    $client = new Client();
    $credentials = base64_encode('username:password');
    $response = $client->get('url',
            [
                'headers' => [
                    'Authorization' => 'Basic ' . $credentials,
                ],
            ]);
    
    打赏 评论

相关推荐 更多相似问题