需要在guzzle请求上设置标题

时间:2017-05-01 17:51:28

标签: guzzle drupal-8

我需要在下面的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);
?>

1 个答案:

答案 0 :(得分:0)

当我需要在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。