Guzzle中间件如何修改参数?
How to modify parameters in Guzzle middleware?
我想为 Guzzle that adds a specific key to the form_params
and populates it with a value. In the docs I have read 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()
进行 urlencode 后成为请求的 body,其次,'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()
);
}));
我想为 Guzzle that adds a specific key to the form_params
and populates it with a value. In the docs I have read 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()
进行 urlencode 后成为请求的 body,其次,'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()
);
}));