php 如何在 Guzzle 中设置默认标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17766626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set default header in Guzzle?
提问by Jürgen Paul
$baseUrl = 'http://foo';
$config = array();
$client = new Guzzle\Http\Client($baseUrl, $config);
What's the new way to set the default header for Guzzle without passing it as a parameter on every $client->post($uri, $headers)
?
为 Guzzle 设置默认标头而不将其作为参数传递给 each 的新方法是什么$client->post($uri, $headers)
?
There's $client->setDefaultHeaders($headers)
but it's deprecated.
有,$client->setDefaultHeaders($headers)
但已弃用。
setDefaultHeaders is deprecated. Use the request.options array to specify default request options
采纳答案by drj201
$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'));
See here:
看这里:
http://docs.guzzlephp.org/en/5.3/clients.html#request-options
http://docs.guzzlephp.org/en/5.3/clients.html#request-options
回答by tasmaniski
If you are using Guzzle v=6.0.*
如果您使用 Guzzle v=6.0.*
$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
read the doc, there are more options.
阅读文档,有更多选择。
回答by stikman
Correct, the old method has been marked as @deprecated. Here is the new suggested method of setting default headers for multiple requests on the client.
正确,旧方法已被标记为@deprecated。这是为客户端上的多个请求设置默认标头的新建议方法。
// enter base url if needed
$url = "";
$headers = array('X-Foo' => 'Bar');
$client = new Guzzle\Http\Client($url, array(
"request.options" => array(
"headers" => $headers
)
));
回答by stikman
This works for me if you are doing it with drupal;
如果您使用 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);