我想为Guzzle写一个中间件它将特定的键添加到 form_params
并用值填充它。在我读过的文档中how to modify the headers但尚未找到有关 $request
对象其他属性的任何信息。按照文档中的示例,这就是我所拥有的:
$key = 'asdf';
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) use ($key) {
// TODO: Modify the $request so that
// $form_params['api_key'] == 'default_value'
return $request;
}));
$client = new Client(array(
'handler' => $stack
));
中间件应该修改请求,以便:
$client->post('example', array(
'form_params' => array(
'foo' => 'some_value'
)
));
与此具有相同的效果:
$client->post('example', array(
'form_params' => array(
'foo' => 'some_value',
'api_key' => 'default_value'
)
));
最佳答案
做过类似的事情后,我可以说这非常简单。
如果您引用 GuzzleHttp\Client 当您将数组传递到“form_params”输入选项中的请求时,会发生两件事。首先,数组的内容在使用 http_build query()
进行 urlencoded 后成为请求的正文,其次,“Content-Type” header 设置为“x-www-form-urlencoded”
下面的代码片段类似于您正在寻找的内容。
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
// perform logic
return new GuzzleHttp\Psr7\Request(
$request->getMethod(),
$request->getUri(),
$request->getHeaders(),
http_build_query($added_parameters_array) . '&' . $request->getBody()->toString()
);
}));
关于middleware - 如何修改Guzzle中间件中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32846892/