$baseUrl = 'http://foo';
$config = array();
$client = new Guzzle\Http\Client($baseUrl, $config);
为Guzzle设置默认标头而不将其作为每个$client->post($uri, $headers)
的参数传递的新方法是什么?
有$client->setDefaultHeaders($headers)
但已被弃用。
setDefaultHeaders is deprecated. Use the request.options array to specify default request options
答案 0 :(得分:31)
如果您使用的是Guzzle v = 6.0。*
$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
read the doc,还有更多选择。
答案 1 :(得分:22)
$client = new Guzzle\Http\Client();
// Set a single header using path syntax
$client->setDefaultOption('headers/X-Foo', 'Bar');
// Set all headers
$client->setDefaultOption('headers', array('X-Foo' => 'Bar'));
见这里:
http://docs.guzzlephp.org/en/latest/http-client/client.html#request-options
答案 2 :(得分:3)
正确,旧方法已标记为@deprecated。以下是为客户端上的多个请求设置默认标头的新建议方法。
// enter base url if needed
$url = "";
$headers = array('X-Foo' => 'Bar');
$client = new Guzzle\Http\Client($url, array(
"request.options" => array(
"headers" => $headers
)
));
答案 3 :(得分:1)
如果您使用drupal进行此操作,这对我有用;
<?php
$url = 'https://jsonplaceholder.typicode.com/posts';
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify' => false,
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);
答案 4 :(得分:0)
为了给 Guzzle 客户端设置默认标头(如果使用客户端作为多个请求的基础),最好设置一个中间件,它会在每个请求上添加标头。否则额外的请求标头将在新的客户端请求中被覆盖。
例如:
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
...
$handler = HandlerStack::create();
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('Authorization', "Bearer {$someAccessToken}");
}));
$client = new Client([
'base_uri' => 'https://example.com',
'handler' => $handler,
]);