Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to set headers on guzzle request

I need to add the type of headers to the guzzle request below, but cannot figure out how to put it in without getting an error This is what I want to add :

$command->set('command.headers', array('content-type' => 'application/x-www-form-urlencoded

to this code below:

<?php
  $url = "https://jsonplaceholder.typicode.com/posts";
  $client = \Drupal::httpClient();

  $post_data = array('color' => 'red');
  $response = $client->request('POST', $url, [
    'form_params' => $post_data,
    'verify' => false
    ]);
  $body = $response->getBody();
  dsm($body);
?>

1 Answers

When I needed use the Guzzle at D8 to make a POST I passed the Content-Type like this:

$url = "https://jsonplaceholder.typicode.com/posts";
  $client = \Drupal::httpClient();

  $post_data = array('color' => 'red');
  $response = $client->request('POST', $url, [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => rawData($post_data),
  ]);
  $body = $response->getBody()->getContents();
  $status = $response->getStatusCode();

A good idea is use the D8 Dependency Injection to pass the HTTP_CLIENT.

like image 81
Adriano Pulz Avatar answered Oct 22 '25 04:10

Adriano Pulz