需要在 guzzle 请求上设置 headers

need to set headers on guzzle request

我需要将 headers 的类型添加到下面的 guzzle 请求中,但无法弄清楚如何在不出错的情况下将其放入 这是我要添加的内容:

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

下面这段代码:

<?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);
?>

当我需要在 D8 处使用 Guzzle 制作 POST 时,我像这样传递了 Content-Type:

$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();

一个好主意是使用 D8 依赖注入来传递 HTTP_CLIENT。