I am creating multiple of the following GuzzleHttp\Psr7\Requests:
use GuzzleHttp\Psr7\Request;
$myRequest = new Request(
'GET',
$someUri
);
And save them in an array: $guzzleRequests
I then create a pool to simultaneously execute all requests:
use GuzzleHttp\Pool;
$testPool = new Pool($testClient = new \GuzzleHttp\Client(), $guzzlePromises,
[
'fulfilled' => function ($response, $index) {
// this is delivered each successful response
var_dump($response);
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
var_dump($reason);
}
]);
// Initiate the transfers and create a promise
$promise = $testPool->promise();
// Force the pool of requests to complete.
$promise->wait();
(Taken from the Doc: http://guzzle.readthedocs.org/en/latest/quickstart.html under "Concurrent requests")
This works for requests to URIs that don't need authentication and returns a 200 OK Status.
How do I add authentication to the Request so that the Pool can run multiple requests against Basic HTTP Authorization protected APIs at the same time?
In response to pinkal vansia: I added the header as you suggested:
$headers = [
'Authorization: Basic '. base64_encode($this->username.':'.$this->password),
];
$myRequest = new Request(
'GET',
$url,
$headers
);`
and dumped the headers:
array (size=2)
'Host' =>
array (size=1)
0 => string '<myHost>' (length=27)
0 =>
array (size=1)
0 => string 'Authorization: Basic <veryLongAuthenticationString>' (length=<stringLength>)`
The response still yields unauthorized:
private 'reasonPhrase' => string 'Unauthorized' (length=12)
private 'statusCode' => int 401
I finally got it running. It turns out, pinkal vansia was already pretty close.
The exact form was the last problem. Michael Downling's comment brought me on the right track.
The Authorization header is the way to go and it needs to be a key => value mapping.
The final thing looks like this:
$url = $myUrl.'?'.http_build_query($this->queryArray);
// ------------ Specify Authorization => key to make it work!!!
$headers = [
'Authorization' => 'Basic '. base64_encode($this->username.':'.$this->password)
];
// -----------------------------------------------------------
$myRequest = new Request(
'GET',
$url,
$headers
);
return $myRequest;
You can add Basic Authentication header in Request as below
$headers = [
'Authorization: Basic '. base64_encode($this->username.':'.$this->password)
];
$myRequest = new Request(
'GET',
$url,
$headers
);
I hope this Helps.
UPDATE
As @worps pointed out header
needs to be a key => value
pair. so final solution is like below,
$headers = [
'Authorization' => 'Basic '. base64_encode($this->username.':'.$this->password)
];
$myRequest = new Request(
'GET',
$url,
$headers
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With