Replacement of drupal_http_request in drupal 8

Public

Warning message

We recommend you to assign at least one category to this snippet so you could easily navigate it in the future. Edit your snippet here.

Get raw version
php
  1. Drupal 7
  2.  
  3. $url = 'testdomain/url';
  4. $response = drupal_http_request($url, array('method' => 'POST', 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8')));
  5. if ($response->code == "200") {
  6. $result = $response->data;
  7. }
  8.  
  9. Drupal 8
  10.  
  11. try {
  12. $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'text/plain')));
  13. $data = (string) $response->getBody();
  14. if (empty($data)) {
  15. return FALSE;
  16. }
  17. }
  18. catch (RequestException $e) {
  19. return FALSE;
  20. }