How to combine query string parameters on request and query parameters using Guzzle?

When I run the following code (using the latest Guzzle, v6), the requested URL http://example.com/foobar?foo=bar removes boo=far from the request.

 $guzzle_http_client = new GuzzleHttp\Client([ 'base_uri' => 'http://example.com/', 'query' => [ 'foo' => 'bar' ], ]); $request = new \GuzzleHttp\Psr7\Request('GET', 'foobar?boo=far'); $response = $guzzle_http_client->send($request); 

When I run the following code, passing boo=far instead as part of the Client::send() method, the requested URL is http://example.com/foobar?boo=far

 $guzzle_http_client = new GuzzleHttp\Client([ 'base_uri' => 'http://example.com/', 'query' => [ 'foo' => 'bar' ], ]); $request = new \GuzzleHttp\Psr7\Request('GET', 'foobar'); $response = $guzzle_http_client->send($request, ['query' => ['boo' => 'far']]); 

Of course, the URL I want to get is:

 http://example.com/foobar?foo=bar&bar=foo 

How to get Guzzle to combine default client request string parameters with query parameters?

+6
source share
1 answer

You can try to get the default β€œquery” parameters using the getConfig method and then combine them with the new β€œquery” parameters, here is an example:

 $client = new GuzzleHttp\Client([ 'base_uri' => 'http://example.com/', 'query' => ['foo' => 'bar'] ]); 

And then you can easily send a GET request:

 $client->get('foobar', [ 'query' => array_merge( $client->getConfig('query'), ['bar' => 'foo'] ) ]); 

You can find more information here. Request parameters

+6
source

Source: https://habr.com/ru/post/989145/


All Articles