Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Guzzle中设置默认标题?_Php_Guzzle - Fatal编程技术网

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

Php 如何在Guzzle中设置默认标题?,php,guzzle,Php,Guzzle,设置Guzzle的默认标题的新方法是什么,而不将其作为参数传递给每个$client->post($uri,$headers) 有$client->setDefaultHeaders($headers),但它已被弃用 $baseUrl = 'http://foo'; $config = array(); $client = new Guzzle\Http\Client($baseUrl, $config); 请看这里: 正确,旧方法已标记为@deprecated。下面是为客户端上的多个请求设置默

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

$client->setDefaultHeaders($headers)
,但它已被弃用

$baseUrl = 'http://foo';
$config = array();
$client = new Guzzle\Http\Client($baseUrl, $config);
请看这里:


正确,旧方法已标记为@deprecated。下面是为客户端上的多个请求设置默认头的新建议方法

$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'));

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

// enter base url if needed
$url = ""; 
$headers = array('X-Foo' => 'Bar');

$client = new Guzzle\Http\Client($url, array(
    "request.options" => array(
       "headers" => $headers
    )
));

,有更多的选择。

如果您使用drupal,这对我很有用

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

如何对基本身份验证用户名和密码执行相同操作?在Guzzle 6中,您只能在客户端实例化时设置默认选项。如果必须使用现有实例,则无法再对其进行配置。看见“哦,嘿,让我们让事情变得不那么灵活,只是因为。会看起来更灵活。”。叹气。当你想做单元测试并且想把客户机注入到你的类中时,这是如何工作的?根据文档的标题是请求选项,而不是客户机选项。两者都是可互换的吗?您可以在客户端实例中设置它,但键“headers”=>[…](如上所示)。没有测试它,但假设它可以更改…有人知道如何在客户机实例化后添加默认头吗?
$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
<?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);