在我的PHP Guzzle客户端代码中,我有类似
的内容$c = new Client('http://test.com/api/1.0/function');
$request = $c->get('?f=4&l=2&p=3&u=5');
但我希望有类似的东西:
$request->set('f', 4);
$request->set('l', 2);
$request->set('p', 3);
$request->set('u', 5);
Guzzle有可能吗?从文档和随机谷歌搜索它似乎是,但我找不到确切的方式。
答案 0 :(得分:14)
你可以:
$c = new Client('http://test.com/api/1.0/function');
$request = $c->get();
$q = $request->getQuery();
$q->set('f', 4);
$q->set('l', 2);
$q->set('p', 3);
$q->set('u', 5);
答案 1 :(得分:3)
狂饮6-您可以使用查询选项参数
// Send a GET request to /get?foo=bar
$client->request('GET', '/get', ['query' => ['foo' => 'bar']]);
http://docs.guzzlephp.org/en/stable/request-options.html#query
答案 2 :(得分:-1)
看看Guzzle文档https://docs.guzzlephp.org/en/stable/request-options.html 如您所见,它具有RequestOptions。 RequestOptions是常量。它们在GuzzleHttp \ RequestOptions中定义。您可以查看类源代码,然后在此处查看所有源代码。因此,为了保持良好且专业的编程风格,您可以编写以下源代码,例如
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
class DataClass extends BaseClass
{
const DEFAULT_ACCEPT_HEADER = 'application/json';
const DEFAULT_CACHE_HEADER = 'no-cache';
private function getData(array $ids)
{
$client = new Client([
'base_uri' => env("HTTP_HOST"),
'timeout' => env("TIMEOUT")
]
);
$response = $client->request('GET', env('ENDPOINT'),
[
RequestOptions::HEADERS => [
'Accept' => self::DEFAULT_ACCEPT_HEADER,
'Cache-Control' => self::DEFAULT_CACHE_HEADER,
],
RequestOptions::QUERY => [
'ids' => implode(',', $ids),
'stats' => 1
]
]
);
return json_decode($response->getBody(), JSON_OBJECT_AS_ARRAY);
}