6

In Drupal 7 I am using the following code.

$url = 'testdomain/url';
$response = drupal_http_request($url, array('method' => 'POST', 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8')));
if ($response->code == "200") {
  $result = $response->data;
}

What is the equivalent code I should use on Drupal 8?

11

Finally i find a code in https://api.drupal.org/api/drupal/core%21includes%21install.core.inc/8 (1375)

and its working for me :)

 try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'text/plain')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }
  }
  catch (RequestException $e) {
    return FALSE;
  }

Hope this will help for some one

2

HTTP client library added to replace drupal_http_request()

$client = \Drupal::httpClient();
$request = $client->createRequest('GET', $feed->url);
$request->addHeader('If-Modified-Since', gmdate(DATE_RFC1123, $last_fetched));

try {
  $response = $client->get($feed->uri, [
    'headers' => [
      'If-Modified-Since' => gmdate(DATE_RFC1123, $last_fetched),
    ],
  ]);
  // Expected result.
  // getBody() returns an instance of Psr\Http\Message\StreamInterface.
  // @see http://docs.guzzlephp.org/en/latest/psr7.html#body
  $data = $response->getBody();
}
catch (RequestException $e) {
  watchdog_exception('my_module', $e);
}
  • 1
    Not Working :( "The website encountered an unexpected error. Please try again later.) Watchdog error is : Recoverable fatal error: Argument 3 passed to GuzzleHttp\Client::request() must be of the type array, string given, called in /var/www/drupal8/vendor/guzzlehttp/guzzle/src/Client.php on line 87 and defined in GuzzleHttp\Client->request() (line 126 of /var/www/drupal8/vendor/guzzlehttp/guzzle/src/Client.php) – visabhishek Jan 22 '16 at 6:28
  • They fixed it, but yeah, change records are the first place to check :) – wizonesolutions Jan 23 '16 at 7:16
  • The code above uses $last_fetched var which is not defined anywhere and also in one place uses $feed->url and in onther $feed->uri – Marko Blazekovic Sep 14 '18 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.