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

Jür*_*aul 31 php guzzle

$baseUrl = 'http://foo';
$config = array();
$client = new Guzzle\Http\Client($baseUrl, $config);
Run Code Online (Sandbox Code Playgroud)

为Guzzle设置默认标头而不将其作为参数传递给每个人的新方法是什么$client->post($uri, $headers)

$client->setDefaultHeaders($headers),但它是不推荐使用.

setDefaultHeaders is deprecated. Use the request.options array to specify default request options
Run Code Online (Sandbox Code Playgroud)

tas*_*ski 32

如果您使用的是Guzzle v = 6.0.*

$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
Run Code Online (Sandbox Code Playgroud)

阅读文档,还有更多选择.

  • 客户端实例化后,是否有人知道如何添加默认标头? (8认同)

drj*_*201 26

$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'));
Run Code Online (Sandbox Code Playgroud)

看这里:

http://docs.guzzlephp.org/en/latest/http-client/client.html#request-options

  • 在Guzzle 6中,您只能在客户端实例化时设置默认选项.如果必须使用现有实例,则无法再对其进行配置.请参阅[什么替换client-> setDefaultOption?](https://github.com/guzzle/guzzle/issues/1419)."哦,嘿,让我们不那么灵活,只是因为.看起来很多[企业](https://github.com/EnterpriseQualityCoding/FizzBu​​zzEnterpriseEdition)".叹. (10认同)

小智 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
    )
));
Run Code Online (Sandbox Code Playgroud)