2015-06-15 30 views
6

當我運行下面的代碼(使用最新的Guzzle,v6)時,獲取請求的URL是http://example.com/foobar?foo=bar從請求中刪除boo=far如何使用Guzzle結合默認查詢字符串參數和特定於請求的參數?

$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); 

當我運行下面的代碼,通過boo=far而不是作爲Client::send()方法的一部分,被請求的URL是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']]); 

當然,我希望被請求的URL是:

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

我該如何使Guzzle結合默認的客戶端查詢字符串參數與特定於請求的參數?

+0

這是一個真正的痛苦!我用靜態方法'withQueryValue'創建了PSR7 \ Uri對象並將其傳遞給構造函數。但它也沒用! –

回答

6

你可以嘗試讓使用「getConfig」方法默認「查詢」選項,然後用新的「查詢」選項,這裏的例子將它們合併:

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

然後你就可以輕鬆發送GET請求:

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

其他信息,你可以在這裏找到Request Options