php - How to add authentication to GuzzleHTTP Request Objects for asynchronous processing -
i creating multiple of following guzzlehttp\psr7\requests:
use guzzlehttp\psr7\request; $myrequest = new request( 'get', $someuri );
and save them in array: $guzzlerequests
i create pool simultaneously execute requests:
use guzzlehttp\pool; $testpool = new pool($testclient = new \guzzlehttp\client(), $guzzlepromises, [ 'fulfilled' => function ($response, $index) { // delivered each successful response var_dump($response); }, 'rejected' => function ($reason, $index) { // delivered each failed request var_dump($reason); } ]); // initiate transfers , create promise $promise = $testpool->promise(); // force pool of requests complete. $promise->wait();
(taken doc: http://guzzle.readthedocs.org/en/latest/quickstart.html under "concurrent requests")
this works requests uris don't need authentication , returns 200 ok status.
how add authentication request pool can run multiple requests against basic http authorization protected apis @ same time?
*edit 1:
in response pinkal vansia: added header suggested:
$headers = [ 'authorization: basic '. base64_encode($this->username.':'.$this->password), ]; $myrequest = new request( 'get', $url, $headers );`
and dumped 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
* final edit:
i got running. turns out, pinkal vansia pretty close.
the exact form last problem. michael downling's comment brought me on right track.
the authorization header way go , needs key => value mapping.
the final thing looks this:
$url = $myurl.'?'.http_build_query($this->queryarray); // ------------ specify authorization => key make 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 below
$headers = [ 'authorization: basic '. base64_encode($this->username.':'.$this->password) ]; $myrequest = new request( 'get', $url, $headers );
i hope helps.
update
as @worps pointed out header
needs key => value
pair. final solution below,
$headers = [ 'authorization' => 'basic '. base64_encode($this->username.':'.$this->password) ]; $myrequest = new request( 'get', $url, $headers );
Comments
Post a Comment