it-swarm.com.de

Was entspricht einem Aufruf von drupal_http_request ()?

In Drupal 7 verwende ich den folgenden 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;
}

Was ist der äquivalente Code, den ich für Drupal 8) verwenden sollte?

9
visabhishek

Schließlich finde ich einen Code in https://api.drupal.org/api/drupal/core%21includes%21install.core.inc/8 (1375)

und es funktioniert für mich :)

 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;
  }

Hoffe das wird jemandem helfen

13
visabhishek

HTTP-Client-Bibliothek hinzugefügt, um drupal_http_request () zu ersetzen

$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);
}
2
Adi

Dies funktioniert bei mir, wenn eine XML-Datei mit\Drupal :: httpClient () POST gesendet wird

$endpoint  = 'http://example.com/something';
$xml = '<>'; // You're XML here.

// Make the request.
$options = [
  'connect_timeout' => 30,
  'debug' => true,
  'headers' => array(
    'Content-Type' => 'text/xml',
  ),
  'body' => $xml,
  'verify'=>true,
];

try {
  $client = \Drupal::httpClient();
  $request = $client->request('POST',$endpoint,$options);

}
catch (RequestException $e){
  // Log the error.
  watchdog_exception('custom_modulename', $e);
}

$responseStatus = $request->getStatusCode();
$responseXml = $request->getBody()->getContents();

Hoffe das hilft.

Weitere Informationen zu Guzzle finden Sie hier: http://docs.guzzlephp.org/en/latest/index.html

1
Karim Boudjema