48
$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
4

5 回答 5

53

如果您使用 Guzzle v=6.0.*

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

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

于 2015-08-10T19:02:44.483 回答
40
$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/5.3/clients.html#request-options

于 2013-07-20T21:00:15.480 回答
4

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

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

$client = new Guzzle\Http\Client($url, array(
    "request.options" => array(
       "headers" => $headers
    )
));
于 2014-02-03T19:14:48.823 回答
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);
于 2017-05-02T19:40:23.133 回答
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,
]);

中间件文档

于 2021-06-30T13:49:40.017 回答