有没有办法使用 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
最佳答案
根据 Creating a client您可以设置“任意数量的默认请求选项”并在 GuzzleHttp\Client Source Code 上
$client = new Client['form_params' => [form values],]);
会将您的 form_params 应用于每个请求。
由于在 Client::applyOptions 中更改了 Content-Type
header ,这可能会导致 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()
);
});
关于php - guzzle 6 的默认 form_params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703647/