Set request options after initialisation in guzzle 6

In Guzzle with version < 6 I used to set my authentication header on the fly after the initialisation of the client. I used setDefaultOption() for this.

$client = new Client(['base_url' => $url]);
$client->setDefaultOption('auth', [$username, $password]);

However this functionality seems to be deprecated in version 6. How would I go about this?

Note: the reason I need to do it this way is because I'm using guzzle for batch requests where some requests need different authentication parameters.


The best option for Guzzle 6+ is to recreate the Client. Guzzle's HTTP client is now immutable, so whenever you want to change something you should create a new object.

This doesn't mean that you have to recreate the whole object graph, HandlerStack and middlewares can stay the same:

use GuzzleHttpClient;
use GuzzleHttpHandlerStack;

$stack = HandlerStack::create();
$stack->push(Middleware::retry(/* ... */));
$stack->push(Middleware::log(/* ... */));

$client = new Client([
    'handler' => $stack,
    'base_url' => $url,
]);

// ...

$newClient = new Client([
    'handler' => $stack,
    'base_url' => $url,
    'auth' => [$username, $password]
]);

You can send the 'auth' param, while constructing the client or sending the request.

$client = new Client(['base_url' => $url, 'auth' => ['username', 'password', 'digest']]);

OR

$client->get('/get', ['auth' => ['username', 'password', 'digest']]);

The other way is to rewrite the requestAsync method and add your custom logic in it. But there is no reason for that.

链接地址: http://www.djcxy.com/p/86868.html

上一篇: 我应该使用哪个第三方Imageview类?

下一篇: 在guzzle 6中初始化后设置请求选项