$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
$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
阅读文档,还有更多选项。
// enter base url if needed
$url = "";
$headers = array('X-Foo' => 'Bar');
$client = new Guzzle\Http\Client($url, array(
"request.options" => array(
"headers" => $headers
)
));
<?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);
例如:
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,
]);