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で使用する必要がある同等のコードは何ですか?

回答:


13

最後に、https://api.drupal.org/api/drupal/core%21includes%21install.core.inc/8(1375)でコードを見つけます

そして私のために働く:)

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

これが誰かのために役立つことを願っています


2

drupal_http_request()を置き換えるために追加されたHTTPクライアントライブラリ

$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
動作していません:( "Webサイトで予期しないエラーが発生しました。後で再試行してください。)ウォッチドッグエラー:回復可能な致命的エラー:GuzzleHttp \ Client :: request()に渡される引数3は、配列の文字列で、指定された文字列で呼び出される必要があります/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を使用し、1か所では$ 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をご覧ください。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.