有没有办法通过guzzle 6向所有请求全局添加form_params?
例如:
$client = new \GuzzleHttp\Client([
'global_form_params' => [ // This isn't a real parameter
'XDEBUG_SESSION_START' => '11845',
'user_token' => '12345abc',
]
]);
$client->post('/some/web/api', [
'form_params' => [
'some_parameter' => 'some value'
]
]);
在我的理想世界中,post
会得到array_merge-ing global_form_params
和form_params
的结果:
[
'XDEBUG_SESSION_START' => '11845',
'user_token' => '12345abc',
'some_parameter' => 'some value',
]
对于query
或json
答案 0 :(得分:2)
根据Creating a client,您可以设置"任意数量的默认请求选项"并在GuzzleHttp\Client Source Code
$client = new Client['form_params' => [form values],]);
会将您的form_params应用于每个请求。
由于在Client::applyOptions内更改Content-Type
标头,这可能会导致GET请求出现问题。它最终将取决于服务器配置。
如果您的意图是让客户端同时发出GET和POST请求,那么将form_params移动到中间件可能会更好。例如:
$stack->push(\GuzzleHttp\Middleware::mapRequest(function (RequestInterface $request) {
if ('POST' !== $request->getMethod()) {
// pass the request on through the middleware stack as-is
return $request;
}
// add the form-params to all post requests.
return new GuzzleHttp\Psr7\Request(
$request->getMethod(),
$request->getUri(),
$request->getHeaders() + ['Content-Type' => 'application/x-www-form-urlencoded'],
GuzzleHttp\Psr7\stream_for($request->getBody() . '&' . http_build_query($default_params_array)),
$request->getProtocolVersion()
);
});