相当于调用drupal_http_request()?


9

在Drupal 7中,我使用以下代码。

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

我应该在Drupal 8上使用的等效代码是什么?

Answers:



2

添加了HTTP客户端库以替换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
不起作用:(“该网站遇到意外错误。请稍后重试。 /var/www/drupal8/vendor/guzzlehttp/guzzle/src/Client.php在第87行并在GuzzleHttp \ Client-> request()中定义(/ var / www / drupal8 / vendor / guzzlehttp:// guzzle / src的第126行/Client.php)
visabhishek


他们修复了它,但是是的,更改记录是检查的第一处:)
wizonesolutions

上面的代码使用$ last_fetched var,该变量未在任何地方定义,并且在一个地方也使用$ feed-> url,在另一位置使用$ feed-> uri
Marko Blazekovic

1

这对我有用,使用\ Drupal :: httpClient()POST发送XML文件

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

希望这可以帮助。

有关Guzzle的更多信息,请访问:http ://docs.guzzlephp.org/en/latest/index.html

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.