如何在Guzzle中设置默认标题?

问题描述 投票:0回答:5
$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
    
php guzzle
5个回答
64
投票
如果您使用的是 Guzzle v=6.0.*

$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);

阅读文档,还有更多选项。


48
投票
$client = new Guzzle\Http\Client(); // Set a single header using path syntax $client->setDefaultOption('headers/X-Foo', 'Bar'); // Set all headers $client->setDefaultOption('headers', ['X-Foo' => 'Bar']);
看这里:

http://docs.guzzlephp.org/en/5.3/clients.html#request-options


5
投票
正确,旧方法已被标记为@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
投票
如果您使用 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);
    

1
投票
要为 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, ]);

中间件文档

© www.soinside.com 2019 - 2024. All rights reserved.