2

I'm having some problems to send consecutive request with digest auth.

Only the first one is working as expected, the second one throw Request Exception with status code 401 (Unauthorized) , that means is losing credentials after first request.

Follow de Code:

class Alice
{
    /**
     * @var GuzzleHttpClient
     */
    private $httpClient;

    public function __construct(GuzzleHttpClient $client)
    {
        $this->httpClient = $client;
    }

    public function getAll(array $data)
    {
        $return = array();
        foreach ($data as $uri) {
            $return[] = $this->callEndpoint($uri);
        }
        return $return;
    }

    private function callEndpoint($uri)
    {
        $httpClient = $this->httpClient;
        $response = $httpClient->get(
            'http://foo.net/bar/' . $uri,
            $this->requestOptions()
        );
        return $response->json();
    }

    private function requestOptions()
    {
        return array(
            'auth' => array(
                'user',
                'password',
                'digest'
            ),
            'headers' => array(
                'Accept'=>'application/vnd.foo+json; version=1.0',
            ),
        );
    }
}

I Resolve it creating new instance of httpClient

  $httpClient = new $this->httpClient;

But i don't thing this is the best solution.

Can i resolve it without creating a new instance?

Markomafs
  • 546
  • 4
  • 19

1 Answers1

1

Short answer: yes it is possible to do multiple requests without having to create new instances of the client.

Long answer: the issue you are experiencing is the fact that your options are being placed onto the request object and not the client object. Multiple subsequent requests can be made if you place the options onto your client like:

use GuzzleHttp\Client;
$client = new Client([
    'base_url' => ['https://api.twitter.com/{version}/', ['version' => 'v1.1']],
    'defaults' => [
        'headers' => ['Foo' => 'Bar'],
        'query'   => ['testing' => '123'],
        'auth'    => ['username', 'password'],
        'proxy'   => 'tcp://localhost:80'
    ]
]);`

The code snippet above comes from the Guzzle Docs on Creating Clients

In response to the comment: there is also the method:

$client->setDefaultOption()

as seen in the Client Source Code

Or you can modify your DIC...

Shaun Bramley
  • 1,989
  • 11
  • 16
  • this is not possible because my GuzzleHttp\Client belongs to Service Container. and i thing it could works onto the request object, because i reset it every request. it can't create a Guzzle\Client object only to hit a endpoint. – Markomafs Mar 19 '15 at 22:19