How to set default header in Guzzle?
If you are using Guzzle v=6.0.*
$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);
read the doc, there are more options.
$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
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.
// enter base url if needed
$url = "";
$headers = array('X-Foo' => 'Bar');
$client = new Guzzle\Http\Client($url, array(
"request.options" => array(
"headers" => $headers
)
));
This works for me if you are doing it with 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);