[php][pear]HTTP_Request2のサンプル#5

Written by uechoco 1月 21

この記事は、HTTP_Requestのマニュアルに載っている全サンプルコードをHTTP_Request2対応で書き換えてみる企画の最終回(5回目)です。HTTP_Request2クラスの概要を知りたい方は、下記リンクの#1を参照ください。

全記事へのリンク:

#13 ダウンロード進捗バー(コマンドラインのみ)

php:
  1. <?php
  2. /**
  3.  * 例 48-13 ダウンロード進捗バー(コマンドラインのみ)
  4.  *
  5.  * @link http://pear.php.net/manual/ja/package.http.http-request.listeners.php
  6.  * @see  http://www.php.net/~helly/php/ext/spl/interfaceSplObserver.html
  7.  */
  8. require_once 'HTTP/Request2.php';
  9. require_once 'Console/ProgressBar.php';
  10.  
  11.  
  12. class HTTP_Request2_Observer_Progress implements SplObserver
  13. {
  14.     /**
  15.      * 対象となるファイルのハンドル
  16.      * @var int
  17.      */
  18.     protected $fp;
  19.  
  20.     /**
  21.      * インジケータの表示に使用する Console_ProgressBar のインスタンス
  22.      * @var Console_ProgressBar
  23.      */
  24.     protected $bar;
  25.  
  26.     /**
  27.      * 対象となるファイルの名前
  28.      * @var string
  29.      */
  30.     protected $target = "filename";
  31.  
  32.     /**
  33.      * 受信したファイルのバイト数
  34.      * @var int
  35.      */
  36.     protected $size;
  37.  
  38.     /**
  39.      * 対象となるファイルをオープンする
  40.      * @param string ファイル名
  41.      * @throws HTTP_Request2_Exception
  42.      */
  43.     function setTarget($target)
  44.     {
  45.         $this->target = $target;
  46.         $this->fp = @fopen($target, 'wb');
  47.         if (!$this->fp) {
  48.             throw new HTTP_Request2_Exception("'{$target}' をオープンできません");
  49.         }
  50.     }
  51.  
  52.     /**
  53.      * HTTP_Request2から呼ばれる (例えば、値が変わった時)
  54.      *
  55.      * @param SplSubject $subject
  56.      */
  57.     public function update(SplSubject $subject)
  58.     {
  59.         $event = $subject->getLastEvent();
  60.  
  61.         switch ($event['name']) {
  62.             case 'connect':
  63.                 $this->target = basename($subject->getUrl()->getPath());
  64.                 break;
  65.             case 'receivedHeaders':
  66.                 $headers = $event['data']->getHeader();
  67.                 if (isset($headers['content-disposition']) &&
  68.                     preg_match('/filename="([^"]+)"/', $headers['content-disposition'], $matches)) {
  69.                     $this->setTarget(basename($matches[1]));
  70.                 } else {
  71.                     $this->setTarget($this->target);
  72.                 }
  73.                 $this->bar = new Console_ProgressBar(
  74.                     '* ' . $this->target . ' %fraction% KB [%bar%] %percent%', '=>', '-',
  75.                     79, (isset($headers['content-length'])? round($headers['content-length'] / 1024): 100)
  76.                 );
  77.                 $this->size = 0;
  78.                 break;
  79.             case 'receivedEncodedBodyPart':
  80.             case 'receivedBodyPart':
  81.                 $this->size += strlen($event['data']);
  82.                 $this->bar->update(round($this->size / 1024));
  83.                 fwrite($this->fp, $event['data']);
  84.                 break;
  85.             case 'receivedBody':
  86.                 fclose($this->fp);
  87.                 break;
  88.         }
  89.     }
  90. }
  91.  
  92. try {
  93.     $req = new HTTP_Request2("http://pear.php.net/get/HTML_QuickForm-stable");
  94.  
  95.     $observer = new HTTP_Request2_Observer_Progress();
  96.     $req->attach($observer);
  97.  
  98.     $response = $req->send();
  99.  
  100. } catch (HTTP_Request2_Exception $e) {
  101.     die($e->getMessage());
  102. } catch (Exception $e) {
  103.     die($e->getMessage());
  104. }
  105.  
  106. /*****************************
  107.  * HTTP_Request_Listenerクラスを派生する代わりにSplObserverインターフェースを実装します。
  108.  *
  109.  * このとき、update(SplSubject $subject)メソッドを実装する必要があります。
  110.  * $subjectにはHTTP_Request2が代入されています(HTTP_Request2はSplSubjectの実装クラス)。
  111.  *
  112.  * たいていの場合、HTTP_Request2::getLastEvent()メソッドを呼び出して、イベントを取得します。
  113.  * 使用するアダプタによってはイベントを発生させないことがあります。
  114.  * 例えば、Mockアダプタはイベント発生させません。
  115.  *
  116.  * getLastEvent()メソッドの返り値はarray('name' => string, 'data' => mixed)の配列です。
  117.  * イベントは以下の8種類が用意されています。
  118.  *  - connect
  119.  *  - sentHeaders
  120.  *  - sentBodyPart
  121.  *  - receivedHeaders
  122.  *  - receivedBodyPart
  123.  *  - receivedEncodedBodyPart
  124.  *  - receivedBody
  125.  *  - disconnect
  126.  * イベントの種類によって、データの種類は異なります。
  127.  *****************************/
  128.  
  129. /*
  130.  
  131. // HTTP_Request でのリスナーの使用例です。これは、ファイルの
  132. // ダウンロードと保存を行うと同時に、処理の進捗状況をバーで表示します
  133. //
  134. // 注意すべき点は以下のとおりです
  135. // 1) ブラウザでなく、コンソールから実行しないといけません
  136. // 2) 出力バッファリングを OFF にしないと正常に動作しません
  137.  
  138. require_once 'HTTP/Request.php';
  139. require_once 'HTTP/Request/Listener.php';
  140. require_once 'Console/ProgressBar.php';
  141.  
  142. PEAR::setErrorHandling(PEAR_ERROR_DIE);
  143.  
  144. set_time_limit(0);
  145.  
  146. class HTTP_Request_DownloadListener extends HTTP_Request_Listener
  147. {
  148.     // 対象となるファイルのハンドル
  149.     // @var int
  150.     var $_fp;
  151.  
  152.     // インジケータの表示に使用する Console_ProgressBar のインスタンス
  153.     // @var object
  154.     var $_bar;
  155.  
  156.     // 対象となるファイルの名前
  157.     // @var string
  158.     var $_target;
  159.  
  160.     // 受信したファイルのバイト数
  161.     // @var int
  162.     var $_size = 0;
  163.  
  164.     function HTTP_Request_DownloadListener()
  165.     {
  166.         $this->HTTP_Request_Listener();
  167.     }
  168.  
  169.     // 対象となるファイルをオープンする
  170.     // @param string ファイル名
  171.     // @throws PEAR_Error
  172.     function setTarget($target)
  173.     {
  174.         $this->_target = $target;
  175.         $this->_fp = @fopen($target, 'wb');
  176.         if (!$this->_fp) {
  177.             PEAR::raiseError("'{$target}' をオープンできません");
  178.         }
  179.     }
  180.  
  181.     function update(&$subject, $event, $data = null)
  182.     {
  183.         switch ($event) {
  184.             case 'sentRequest':
  185.                 $this->_target = basename($subject->_url->path);
  186.                 break;
  187.  
  188.             case 'gotHeaders':
  189.                 if (isset($data['content-disposition']) &&
  190.                     preg_match('/filename="([^"]+)"/', $data['content-disposition'], $matches)) {
  191.  
  192.                     $this->setTarget(basename($matches[1]));
  193.                 } else {
  194.                     $this->setTarget($this->_target);
  195.                 }
  196.                 $this->_bar =& new Console_ProgressBar(
  197.                     '* ' . $this->_target . ' %fraction% KB [%bar%] %percent%', '=>', '-',
  198.                     79, (isset($data['content-length'])? round($data['content-length'] / 1024): 100)
  199.                 );
  200.                 $this->_size = 0;
  201.                 break;
  202.  
  203.             case 'tick':
  204.                 $this->_size += strlen($data);
  205.                 $this->_bar->update(round($this->_size / 1024));
  206.                 fwrite($this->_fp, $data);
  207.                 break;
  208.  
  209.             case 'gotBody':
  210.                 fclose($this->_fp);
  211.                 break;
  212.  
  213.             default:
  214.                 PEAR::raiseError("イベント '{$event}' が処理できません");
  215.         } // switch
  216.     }
  217. }
  218.  
  219. // 別のパッケージを使用してもかまいませんが、できるだけ大き目のものを
  220. // 選ばないと進捗バーが見えません
  221. $url = 'http://pear.php.net/get/HTML_QuickForm-stable';
  222.  
  223. $req =& new HTTP_Request($url);
  224.  
  225. $download =& new HTTP_Request_DownloadListener();
  226. $req->attach($download);
  227. $req->sendRequest(false);
  228. */
  229. ?>

最後のサンプルになりましたが、昔のHTTP_Request_Listenerに当たるSplObserver派生クラスのサンプルとなりました。HTTP_Request2のパッケージにはHTTP_Request2_Observer_Logが同梱されているので、そちらを参考にすると、SplObserver派生クラスについての理解が深められます。

全サンプルコードを載せましたが、0.2.0(alpha)の時点でだいたいの機能はそろっている気がしますね。

[php][pear]HTTP_Request2のサンプル#4

Written by uechoco 1月 21

この記事は、HTTP_Requestのマニュアルに載っている全サンプルコードをHTTP_Request2対応で書き換えてみる企画の4回目です。HTTP_Request2クラスの概要を知りたい方は、下記リンクの#1を参照ください。

全記事へのリンク:

#10 レスポンスコードをチェックする

php:
  1. <?php
  2. /**
  3.  * 例 48-10 レスポンスコードをチェックする
  4.  *
  5.  * @link http://pear.php.net/manual/ja/package.http.http-request.response-eval.php
  6.  */
  7. require_once 'HTTP/Request2.php';
  8.  
  9. $urls = array(
  10.     "http://www.example.com/",
  11.     "http://example.com/thisdoesnotexist.html"
  12.     );
  13.  
  14. try {
  15.     $req = new HTTP_Request2();
  16.     foreach ($urls as $url) {
  17.         $req->setUrl($url);
  18.         $response = $req->send();
  19.  
  20.         $code = $response->getStatus();
  21.         switch ($code) {
  22.             case 404:
  23.                 echo "Document not foundn";
  24.                 break;
  25.  
  26.             case 200:
  27.                 echo "Everything's okn";
  28.                 break;
  29.         }
  30.     }
  31.  
  32. } catch (HTTP_Request2_Exception $e) {
  33.     die($e->getMessage());
  34. } catch (Exception $e) {
  35.     die($e->getMessage());
  36. }
  37.  
  38. /*****************************
  39.  * HTTP_Request::getResponseCode()はHTTP_Request2_Response::getStatus()に変更されました。
  40.  *****************************/
  41.  
  42. /*
  43. require_once "HTTP/Request.php";
  44.  
  45. $urls = array(
  46.     "http://www.example.com/",
  47.     "http://example.com/thisdoesnotexist.html"
  48.     );
  49.  
  50. $req =& new HTTP_Request("");
  51. foreach ($urls as $url) {
  52.     $req->setURL($url);
  53.     $req->sendRequest();
  54.  
  55.     $code = $req->getResponseCode();
  56.     switch ($code) {
  57.     case 404:
  58.         echo "Document not foundn";
  59.         break;
  60.  
  61.     case 200:
  62.         echo "Everything's okn";
  63.         break;
  64.  
  65.     }
  66. }
  67.  
  68. */
  69. ?>

#11 レスポンスからの全てのヘッダを取得する

php:
  1. <?php
  2. /**
  3.  * 例 48-11 レスポンスからの全てのヘッダを取得する
  4.  *
  5.  * @link http://pear.php.net/manual/ja/package.http.http-request.response-eval.php
  6.  */
  7. require_once 'HTTP/Request2.php';
  8.  
  9. try {
  10.     $req = new HTTP_Request2("http://example.com/");
  11.     $response = $req->send();
  12.     foreach ($response->getHeader() as $name => $value) {
  13.         echo $name . " = " . $value . "n";
  14.     }
  15.  
  16. } catch (HTTP_Request2_Exception $e) {
  17.     die($e->getMessage());
  18. } catch (Exception $e) {
  19.     die($e->getMessage());
  20. }
  21.  
  22. /*****************************
  23.  * HTTP_Request::getResponseHeader()はHTTP_Request2_Response::getHeader()に変更されました。
  24.  *****************************/
  25.  
  26. /*
  27. require_once "HTTP/Request.php";
  28.  
  29. $req =& new HTTP_Request("http://example.com/");
  30. $req->sendRequest();
  31.  
  32. foreach ($req->getResponseHeader() as $name => $value) {
  33.     echo $name . " = " . $value . "n";
  34. }
  35.  
  36. */
  37. ?>

#12 特定のヘッダを取得する

php:
  1. <?php
  2. /**
  3.  * 例 48-12 特定のヘッダを取得する
  4.  *
  5.  * @link http://pear.php.net/manual/ja/package.http.http-request.response-eval.php
  6.  */
  7. require_once 'HTTP/Request2.php';
  8.  
  9. try {
  10.     $req = new HTTP_Request2("http://example.com/");
  11.     $response = $req->send();
  12.     echo $response->getHeader('Date');
  13.  
  14. } catch (HTTP_Request2_Exception $e) {
  15.     die($e->getMessage());
  16. } catch (Exception $e) {
  17.     die($e->getMessage());
  18. }
  19.  
  20. /*****************************
  21.  * HTTP_Request::getResponseHeader()はHTTP_Request2_Response::getHeader()に変更されました。
  22.  *****************************/
  23.  
  24. /*
  25. require_once "HTTP/Request.php";
  26.  
  27. $req =& new HTTP_Request("http://example.com/");
  28. $req->sendRequest();
  29.  
  30. echo $req->getResponseHeader("Date");
  31.  
  32.  
  33. */
  34. ?>

[php][pear]HTTP_Request2のサンプル#3

Written by uechoco 1月 21

この記事は、HTTP_Requestのマニュアルに載っている全サンプルコードをHTTP_Request2対応で書き換えてみる企画の3回目です。HTTP_Request2クラスの概要を知りたい方は、下記リンクの#1を参照ください。

全記事へのリンク:

#6 PDF 文章をアップロードする

php:
  1. <?php
  2. /**
  3.  * 例 48-6 PDF 文章をアップロードする
  4.  *
  5.  * この例では、/home/johndoe/text.pdf というファイルが
  6.  * リモートにあるマシン upload.example.com に johndoe-text.pdf という名前で
  7.  * アップロードされます。 さらに、ジョンが何かをアップロードする事を許可されていることを
  8.  * 保証するために、Basic 認証が使用されています。
  9.  *
  10.  * @link http://pear.php.net/manual/ja/package.http.http-request.file-upload.php
  11.  */
  12. require_once 'HTTP/Request2.php';
  13.  
  14. try {
  15.     $req = new HTTP_Request2("http://upload.example.com/upload.php", HTTP_Request2::METHOD_POST);
  16.     $req->setAuth("johndoe", "foo", HTTP_Request2::AUTH_BASIC);
  17.     $req->addUpload("johndoe-txt.pdf", "/home/johndoe/text.pdf");
  18.     $response = $req->send();
  19.     echo $response->getBody();
  20. } catch (HTTP_Request2_Exception $e) {
  21.     die($e->getMessage());
  22. } catch (Exception $e) {
  23.     die($e->getMessage());
  24. }
  25.  
  26. /*****************************
  27.  * HTTP_Request::addFile()はHTTP_Request2->addUpload()に変更されました。
  28.  *****************************/
  29.  
  30. /*
  31. require_once "HTTP/Request.php";
  32.  
  33. $req =& new HTTP_Request("http://upload.example.com/upload.php");
  34. $req->setBasicAuth("johndoe", "foo");
  35. $req->setMethod(HTTP_REQUEST_METHOD_POST);
  36.  
  37. $result = $req->addFile("johndoe-txt.pdf", "/home/johndoe/text.pdf");
  38. if (PEAR::isError($result)) {
  39.     echo $result->getMessage();
  40. } else {
  41.  
  42.     $response = $req->sendRequest();
  43.  
  44.     if (PEAR::isError($response)) {
  45.         echo $response->getMessage();
  46.     } else {
  47.         echo $req->getResponseBody();
  48.     }
  49. }
  50. */
  51. ?>

#7 カスタムリクエストヘッダの追加

php:
  1. <?php
  2. /**
  3.  * 例 48-7 カスタムリクエストヘッダの追加
  4.  *
  5.  * 以下の例では、HTTP ヘッダ X-PHP-Version が HTTP リクエストに追加されます。
  6.  * このヘッダの値は、 HTTP_Request  インスタンスが動作している PHP インタプリタのバージョン文字列です。
  7.  *
  8.  * @link http://pear.php.net/manual/ja/package.http.http-request.headers.php
  9.  */
  10. require_once 'HTTP/Request2.php';
  11.  
  12. try {
  13.     $req = new HTTP_Request2("http://example.com/");
  14.     $req->setHeader("X-PHP-Version", phpversion());
  15.  
  16.     $response = $req->send();
  17.     echo $response->getBody();
  18.  
  19. } catch (HTTP_Request2_Exception $e) {
  20.     die($e->getMessage());
  21. } catch (Exception $e) {
  22.     die($e->getMessage());
  23. }
  24.  
  25. /*****************************
  26.  * HTTP_Request::addHeader()はHTTP_Request2->setHeader()に変更されました。
  27.  * 配列での一括指定や"header:value"形式の文字列でも受け付けるようになりました。
  28.  *****************************/
  29.  
  30. /*
  31. require_once "HTTP/Request.php";
  32.  
  33. $req =& new HTTP_Request("http://example.com/");
  34. $req->addHeader("X-PHP-Version", phpversion());
  35.  
  36. $response = $req->sendRequest();
  37.  
  38. if (PEAR::isError($response)) {
  39.     echo $response->getMessage();
  40. } else {
  41.     echo $req->getResponseBody();
  42. }
  43.  
  44. */
  45. ?>

#8 匿名アクセスでプロキシサーバを利用する

php:
  1. <?php
  2. /**
  3.  * 例 48-8 匿名アクセスでプロキシサーバを利用する
  4.  *
  5.  *  この例では、プロキシサーバがポート 8080  で待機しており、
  6.  * example.com への外向き接続の代理(プロキシ)を行っている
  7.  * proxy.example.com というホスト名のマシンを 利用しようとしている、と想定しています。
  8.  *
  9.  * setProxy() の二番目のパラメータはオプションで、 デフォルトは 8080 です。
  10.  *
  11.  * @link http://pear.php.net/manual/ja/package.http.http-request.proxy-auth.php
  12.  */
  13. require_once 'HTTP/Request2.php';
  14.  
  15. try {
  16.     $req = new HTTP_Request2("http://example.com/");
  17.     $req->setConfig(array(
  18.         'proxy_host' => 'proxy.example.com',
  19.         'proxy_port' => '8080',
  20.     ));
  21.     // $req->setConfig('proxy_host', 'proxy.example.com');
  22.     // $req->setConfig('proxy_port', '8080');
  23.  
  24.     $response = $req->send();
  25.     echo $response->getBody();
  26.  
  27. } catch (HTTP_Request2_Exception $e) {
  28.     die($e->getMessage());
  29. } catch (Exception $e) {
  30.     die($e->getMessage());
  31. }
  32.  
  33. /*****************************
  34.  * HTTP_Request::setProxy()に対応するメソッドはありません。
  35.  * 代わりにHTTP_Request2::setConfig()メソッドで1つ1つ設定するか、配列でまとめて設定します。
  36.  *****************************/
  37.  
  38. /*
  39. require_once "HTTP/Request.php";
  40.  
  41. $req =& new HTTP_Request("http://example.com/");
  42. $req->setProxy("proxy.example.com", 8080);
  43. */
  44. ?>

#9 プロキシ認証の利用

php:
  1. <?php
  2. /**
  3.  * 例 48-9 プロキシ認証の利用
  4.  *
  5.  * これは、プロキシサーバでのユーザー認証のためのユーザー名/パスワードの
  6.  * タプルが提供されていることを除いて、上記と同じ例です:
  7.  * ユーザー名は johndoe で付随するパスワードは foo です。
  8.  *
  9.  * @link http://pear.php.net/manual/ja/package.http.http-request.proxy-auth.php
  10.  */
  11. require_once 'HTTP/Request2.php';
  12.  
  13. try {
  14.     $req = new HTTP_Request2("http://example.com/");
  15.     $req->setConfig(array(
  16.         'proxy_host' => 'proxy.example.com',
  17.         'proxy_port' => '8080',
  18.         'proxy_user' => 'johndoe',
  19.         'proxy_password' => 'foo',
  20.     ));
  21.     // $req->setConfig('proxy_host', 'proxy.example.com');
  22.     // $req->setConfig('proxy_port', '8080');
  23.     // $req->setConfig('proxy_user', 'johndoe');
  24.     // $req->setConfig('proxy_password', 'foo');
  25.  
  26.     $response = $req->send();
  27.     echo $response->getBody();
  28.  
  29. } catch (HTTP_Request2_Exception $e) {
  30.     die($e->getMessage());
  31. } catch (Exception $e) {
  32.     die($e->getMessage());
  33. }
  34.  
  35. /*****************************
  36.  * HTTP_Request::setProxy()に対応するメソッドはありません。
  37.  * 代わりにHTTP_Request2::setConfig()メソッドで1つ1つ設定するか、配列でまとめて設定します。
  38.  *****************************/
  39.  
  40. /*
  41. require_once "HTTP/Request.php";
  42.  
  43. $req =& new HTTP_Request("http://example.com/");
  44. $req->setProxy("proxy.example.com", 8080, "johndoe", "foo");
  45.  
  46. */
  47. ?>

[php][pear]HTTP_Request2のサンプル#2

Written by uechoco 1月 21

この記事は、HTTP_Requestのマニュアルに載っている全サンプルコードをHTTP_Request2対応で書き換えてみる企画の2回目です。HTTP_Request2クラスの概要を知りたい方は、下記リンクの#1を参照ください。 全記事へのリンク:

#3 Basic 認証

php:
  1. <?php
  2. /**
  3.  * 例 48-3 Basic 認証
  4.  *
  5.  * @link http://pear.php.net/manual/ja/package.http.http-request.basic-auth.php
  6.  */
  7. require_once 'HTTP/Request2.php';
  8.  
  9. try {
  10.     $req = new HTTP_Request2("http://example.com/protected.html");
  11.     $req->setAuth("johndoe", "foo", HTTP_Request2::AUTH_BASIC);
  12.     $response = $req->send();
  13.     echo $response->getBody();
  14.  
  15. } catch (HTTP_Request2_Exception $e) {
  16.     die($e->getMessage());
  17. } catch (Exception $e) {
  18.     die($e->getMessage());
  19. }
  20.  
  21. /*****************************
  22.  * HTTP_Request::setBasicAuth()はHTTP_Request2->setAuth()に変更されました。
  23.  * 第3引数で認証の種類(AUTH_BASIC、AUTH_DIGEST)が指定できますが、
  24.  * Basic認証(AUTH_BASIC)がデフォルト値なので、今回は省略してもかまいません。
  25.  *****************************/
  26.  
  27. /*
  28. require_once "HTTP/Request.php";
  29.  
  30. $req =& new HTTP_Request("http://example.com/protected.html");
  31. $req->setBasicAuth("johndoe", "foo");
  32.  
  33. $response = $req->sendRequest();
  34.  
  35. if (PEAR::isError($response)) {
  36.     echo $response->getMessage();
  37. } else {
  38.     echo $req->getResponseBody();
  39. }
  40.  
  41. */
  42. ?>

#4 リクエストにクッキーを追加する

php:
  1. <?php
  2. /**
  3.  * 例 48-4 リクエストにクッキーを追加する
  4.  *
  5.  * この例では、version というクッキーが HTTP リクエストに追加されます。
  6.  * このクッキーの値は、 HTTP_Request2 インスタンスが動作している PHP インタプリタのバージョン文字列です。
  7.  *
  8.  * @link http://pear.php.net/manual/ja/package.http.http-request.cookie.php
  9.  */
  10. require_once 'HTTP/Request2.php';
  11.  
  12. try {
  13.     $req = new HTTP_Request2("http://example.com/");
  14.     $req->addCookie("version", phpversion());
  15.     $response = $req->send();
  16.     echo $response->getBody();
  17.  
  18. } catch (HTTP_Request2_Exception $e) {
  19.     die($e->getMessage());
  20. } catch (Exception $e) {
  21.     die($e->getMessage());
  22. }
  23.  
  24. /*****************************
  25.  * HTTP_Request::addCookie()はHTTP_Request2->addCookie()としてそのまま受け継がれています。
  26.  *****************************/
  27.  
  28. /*
  29. require_once "HTTP/Request.php";
  30.  
  31. $req =& new HTTP_Request("http://example.com/");
  32. $req->addCookie("version", phpversion());
  33.  
  34. $response = $req->sendRequest();
  35.  
  36. if (PEAR::isError($response)) {
  37.     echo $response->getMessage();
  38. } else {
  39.     echo $req->getResponseBody();
  40. }
  41. */
  42. ?>

#5 HTTP レスポンスからクッキーを読み込む

php:
  1. <?php
  2. /**
  3.  * 例 48-5 HTTP レスポンスからクッキーを読み込む
  4.  *
  5.  * HTTP レスポンスのクッキーを読み込みは、以下の例で示されます。
  6.  *
  7.  * @link http://pear.php.net/manual/ja/package.http.http-request.cookie.php
  8.  */
  9. require_once 'HTTP/Request2.php';
  10.  
  11. try {
  12.     $req = new HTTP_Request2("http://example.com/");
  13.     $response = $req->send();
  14.     print_r($response->getCookies());
  15.  
  16. } catch (HTTP_Request2_Exception $e) {
  17.     die($e->getMessage());
  18. } catch (Exception $e) {
  19.     die($e->getMessage());
  20. }
  21.  
  22. /*****************************
  23.  * HTTP_Request::getResponseCookies()はHTTP_Request2_Response->getCookies()に変更されました。
  24.  *****************************/
  25.  
  26. /*
  27. require_once "HTTP/Request.php";
  28.  
  29. $req =& new HTTP_Request("http://example.com/");
  30.  
  31. $response = $req->sendRequest();
  32.  
  33. if (PEAR::isError($response)) {
  34.     echo $response->getMessage();
  35. } else {
  36.     print_r($req->getResponseCookies());
  37. }
  38. */
  39. ?>

[php][pear]HTTP_Request2のサンプル#1

Written by uechoco 1月 21

誰もが愛用しているPEAR::HTTP_Requestクラスですが、最近は後継のPEAR::HTTP_Request2クラスがリリースされてちょっと話題になりました。2009/01/21現在、バージョンは0.2.0(alpha)になっています。今後は利用される場面が増えてくると思いますので、HTTP_Requestのマニュアルに載っている全サンプルコードをHTTP_Request2対応で書き換えてみました。ソースコードやAPIリファレンスから推測して書いているので、100%正しいソースコードという保証はできませんが、そこら辺はあなたの技量でカバーしてください(笑。

とはいえ、HTTP_Request2の概要を知らない方も多いと思いますので、まずは0.2.0(alpha)時点でのHTTP_Request2の概要をまとめておきます。

  • 特徴
    • HTTP_RequestをPHP5対応に書きなおした
    • アダプタに対応
      • SocketAdapter : 従来のHTTP_Requestに相当する
      • CurlAdapter : cURL拡張のラッパー
      • MockAdapter : HTTP_Request2に依存しているパッケージのテスト用
    • POSTリクエストにおいて以下の項目に対応
      • データとファイルのアップロード
      • クッキー認証
      • プロキシ
      • gzipとdeflateエンコーディング
      • Observerを用いたリクエスト処理のモニタリング
  • 動作環境
  • 0.3.0のロードマップ
    • Socketアダプタにて、HTTPSプロキシのサポート
    • Socketアダプタにて、ダイジェスト認証のサポート

個人的にはcURL拡張以外でダイジェスト認証が使えるようになるのか?っていうのがちょっと期待しているところです。今まで探してもなかったもので・・・。

さてさて、本題のサンプルですね。HTTP_Requestのマニュアルには、全13個のサンプルソースコードが載っています。ブログが長くなるのも面倒なので、小分けにして紹介していきたいと思います。一応、記述の根拠となるように、変更点もコメントしておきましたので、参考にしてください。

#1 yahoo.com の内容を取得し、それを表示する

php:
  1. /**
  2. * 例 48-1 yahoo.com の内容を取得し、それを表示する
  3. *
  4. * @link http://pear.php.net/manual/ja/package.http.http-request.intro.php
  5. */
  6. require_once 'HTTP/Request2.php';
  7.  
  8. try {
  9. $req = new HTTP_Request2("http://www.yahoo.com/");
  10. $response = $req-&gt;send();
  11. echo $response-&gt;getBody();
  12.  
  13. } catch (HTTP_Request2_Exception $e) {
  14. die($e-&gt;getMessage());
  15. } catch (Exception $e) {
  16. die($e-&gt;getMessage());
  17. }
  18.  
  19. /*****************************
  20. * クラス名はHTTP_Request2になりました。
  21. *
  22. * コンストラクタも内部で使用するメソッドが例外を吐く可能性があるので、
  23. * HTTP_Request2を使用する箇所全体をtry/catchで囲みましょう。
  24. *
  25. * HTTP_Request::sendRequest()はHTTP_Request2-&gt;send()に変更されました。
  26. * このとき、返り値はHTTP_Request2_Responseクラスになります。
  27. *
  28. * HTTP_Request::getResponseBody()はHTTP_Request2_Response::getBody()に変更されました。
  29. *****************************/
  30.  
  31. /*
  32. ///////////////////////////////
  33. // 旧ソースコード
  34. ///////////////////////////////
  35. require_once 'HTTP/Request.php';
  36.  
  37. $req =&amp; new HTTP_Request("http://www.yahoo.com/");
  38. if (!PEAR::isError($req-&gt;sendRequest())) {
  39. echo $req-&gt;getResponseBody();
  40. }
  41. */
  42. ?&gt;

#2 二つの Web サイトの内容を取得し、一行で表示する

php:
  1. /**
  2. * 例 48-2 二つの Web サイトの内容を取得し、一行で表示する
  3. *
  4. * この例では、二つの Web サイトの内容が取得され、表示されます。
  5. * 前者は POST パラメータが処理されます。POST データスタックは、
  6. * 二番目の Web サイトの内容が取得される前にクリアされます。
  7. *
  8. * @link http://pear.php.net/manual/ja/package.http.http-request.intro.php
  9. */
  10. require_once 'HTTP/Request2.php';
  11.  
  12. try {
  13. $req = new HTTP_Request2("http://www.php.net", HTTP_Request2::METHOD_POST);
  14. // $req-&gt;setMethod(HTTP_Request2::METHOD_POST);
  15. $req-&gt;addPostParameter('Foo', 'bar');
  16. $response1 = $req-&gt;send();
  17.  
  18. $req-&gt;setMethod(HTTP_Request2::METHOD_GET);
  19. $req-&gt;setURL("http://pear.php.net");
  20. // $req-&gt;clearPostData();
  21. $response2 = $req-&gt;send();
  22.  
  23. echo $response1-&gt;getBody();
  24. echo $response2-&gt;getBody();
  25.  
  26. } catch (HTTP_Request2_Exception $e) {
  27. die($e-&gt;getMessage());
  28. } catch (Exception $e) {
  29. die($e-&gt;getMessage());
  30. }
  31.  
  32. /*****************************
  33. * クラス名はHTTP_Request2になりました。
  34. *
  35. * HTTP_Request2::setMethod()は健在ですが、コンストラクタの第2引数にHTTPメソッドを指定するのが楽です。
  36. *
  37. * HTTP_Request::addPostData()はHTTP_Request2-&gt;addPostParameter()に変更されました。
  38. * このとき、返り値はHTTP_Request2_Responseクラスになります。
  39. *
  40. * HTTP_Request2::setUrl()は今まで通りURLの文字列を受け付けますが、Net_URL2クラスも受け付けます。
  41. *
  42. * HTTP_Request::clearPostData()に当たるメソッドはHTTP_Request2には見受けられません。
  43. * POSTメソッドの後にGETメソッドを送信しても、HTTP_Request2-&gt;addPostParameter()で設定したパラメータは
  44. * 送信されることはありませんでした。(Wiresharkでパケットキャプチャをして確認済みです)
  45. *****************************/
  46.  
  47. /*
  48. require_once "HTTP/Request.php";
  49.  
  50. $req =&amp; new HTTP_Request("http://www.php.net");
  51. $req-&gt;setMethod(HTTP_REQUEST_METHOD_POST);
  52. $req-&gt;addPostData("Foo", "bar");
  53. if (!PEAR::isError($req-&gt;sendRequest())) {
  54. $response1 = $req-&gt;getResponseBody();
  55. } else {
  56. $response1 = "";
  57. }
  58.  
  59. $req-&gt;setMethod(HTTP_REQUEST_METHOD_GET);
  60. $req-&gt;setURL("http://pear.php.net");
  61. $req-&gt;clearPostData();
  62. if (!PEAR::isError($req-&gt;sendRequest())) {
  63. $response2 = $req-&gt;getResponseBody();
  64. } else {
  65. $response2 = "";
  66. }
  67.  
  68. echo $response1;
  69. echo $response2;
  70.  
  71. */
  72. ?&gt;

全記事へのリンク: