PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/en/core-utility-libraries/httpsocket.rst

https://github.com/hiromi2424/docs
ReStructuredText | 382 lines | 275 code | 107 blank | 0 comment | 0 complexity | d02fe7c109a9d8d4ffe79bb4cc22500a MD5 | raw file
  1. HttpSocket
  2. ##########
  3. .. php:class:: HttpSocket(mixed $config = array())
  4. CakePHP includes an HttpSocket class which can be used easily for
  5. making requests. It is a great way to communicate with external webservices, or
  6. remote apis.
  7. Making a request
  8. ================
  9. You can use HttpSocket to create most kinds of HTTP requests with the different
  10. HTTP methods.
  11. .. php:method:: get($uri, $query, $request)
  12. The ``$query`` parameter, can either be a query string, or an array of keys
  13. and values. The get method makes a simple HTTP GET request returning the
  14. results::
  15. App::uses('HttpSocket', 'Network/Http');
  16. $HttpSocket = new HttpSocket();
  17. // string query
  18. $results = $HttpSocket->get('http://www.google.com/search', 'q=cakephp');
  19. // array query
  20. $results = $HttpSocket->get('http://www.google.com/search', array('q' => 'cakephp'));
  21. .. php:method:: post($uri, $data, $request)
  22. The post method makes a simple HTTP POST request returning the
  23. results.
  24. The parameters for the ``post`` method are almost the same as the
  25. get method, ``$uri`` is the web address where the request is being
  26. made; ``$query`` is the data to be posted, either as a string, or as
  27. an array of keys and values::
  28. App::uses('HttpSocket', 'Network/Http');
  29. $HttpSocket = new HttpSocket();
  30. // string data
  31. $results = $HttpSocket->post(
  32. 'http://example.com/add',
  33. 'name=test&type=user'
  34. );
  35. // array data
  36. $data = array('name' => 'test', 'type' => 'user');
  37. $results = $HttpSocket->post('http://example.com/add', $data);
  38. .. php:method:: put($uri, $data, $request)
  39. The put method makes a simple HTTP PUT request returning the
  40. results.
  41. The parameters for the ``put`` method is the same as the
  42. :php:meth:`~HttpSocket::post()` method.
  43. .. php:method:: delete($uri, $query, $request)
  44. The delete method makes a simple HTTP DELETE request returning the
  45. results.
  46. The parameters for the ``delete`` method is the same as the
  47. :php:meth:`~HttpSocket::get()` method. The ``$query`` parameter can either be a string or an array
  48. of query string arguments for the request.
  49. .. php:method:: patch($uri, $data, $request)
  50. The patch method makes a simple HTTP PATCH request returning the
  51. results.
  52. The parameters for the ``patch`` method is the same as the
  53. :php:meth:`~HttpSocket::post()` method.
  54. .. versionadded:: 2.4
  55. .. php:method:: request($request)
  56. The base request method, which is called from all the wrappers
  57. (get, post, put, delete). Returns the results of the request.
  58. $request is a keyed array of various options. Here is the format
  59. and default settings::
  60. public $request = array(
  61. 'method' => 'GET',
  62. 'uri' => array(
  63. 'scheme' => 'http',
  64. 'host' => null,
  65. 'port' => 80,
  66. 'user' => null,
  67. 'pass' => null,
  68. 'path' => null,
  69. 'query' => null,
  70. 'fragment' => null
  71. ),
  72. 'auth' => array(
  73. 'method' => 'Basic',
  74. 'user' => null,
  75. 'pass' => null
  76. ),
  77. 'version' => '1.1',
  78. 'body' => '',
  79. 'line' => null,
  80. 'header' => array(
  81. 'Connection' => 'close',
  82. 'User-Agent' => 'CakePHP'
  83. ),
  84. 'raw' => null,
  85. 'redirect' => false,
  86. 'cookies' => array()
  87. );
  88. Handling the response
  89. =====================
  90. Responses from requests made with ``HttpSocket`` are instances of
  91. ``HttpResponse``. This object gives you a few accessor methods to access the
  92. contents of an HTTP response. This class implements the
  93. `ArrayAccess <http://php.net/manual/en/class.arrayaccess.php>`_ and
  94. `__toString() <http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring>`_,
  95. so you can continue using the ``$http->response`` as array and the return of
  96. request methods as string::
  97. App::uses('HttpSocket', 'Network/Http');
  98. $http = new HttpSocket();
  99. $response = $http->get('http://www.cakephp.org');
  100. // Check the body for the presence of a title tag.
  101. $titlePos = strpos($response->body, '<title>');
  102. // Get the status code for the response.
  103. $code = $response->code;
  104. The ``HttpResponse`` has the following attributes:
  105. * ``body`` returns body of HTTP response (normally the HTML).
  106. * ``headers`` returns array with headers.
  107. * ``cookies`` returns array with new cookies (cookies from others request are not stored here).
  108. * ``httpVersion`` returns string with HTTP version (from first line in response).
  109. * ``code`` returns the integer with HTTP code.
  110. * ``reasonPhrase`` returns the string with HTTP code response.
  111. * ``raw`` returns the unchanged response from server.
  112. The ``HttpResponse`` also exposes the following methods:
  113. * ``body()`` returns the body
  114. * ``isOk()`` returns if code is 200;
  115. * ``isRedirect()`` returns if code is 301, 302, 303 or 307 and the *Location* header is set.
  116. * ``getHeader()`` allows you to fetch headers, see the next section.
  117. Getting headers from a response
  118. -------------------------------
  119. Following others places in core, the HttpSocket does not change the casing of
  120. headers. :rfc:`2616` states that headers are case insensitive, and HttpSocket
  121. preserves the values the remote host sends::
  122. HTTP/1.1 200 OK
  123. Date: Mon, 16 Apr 2007 04:14:16 GMT
  124. server: CakeHttp Server
  125. content-tyPe: text/html
  126. Your ``$response->headers`` (or ``$response['header']``) will contain the exact
  127. keys sent. In order to safely access the header fields, it's best to use
  128. ``getHeader()``. If your headers looks like::
  129. Date: Mon, 16 Apr 2007 04:14:16 GMT
  130. server: CakeHttp Server
  131. content-tyPe: text/html
  132. You could fetch the above headers by calling::
  133. // $response is an instance of HttpResponse
  134. // get the Content-Type header.
  135. $response->getHeader('Content-Type');
  136. // get the date
  137. $response->getHeader('date');
  138. Headers can be fetched case-insensitively.
  139. Automatically handling a redirect response
  140. ------------------------------------------
  141. When the response has a valid redirect status code (see ``HttpResponse::isRedirect``),
  142. an extra request can be automatically done according to the received *Location* header::
  143. <?php
  144. App::uses('HttpSocket', 'Network/Http');
  145. $HttpSocket = new HttpSocket();
  146. $response = $HttpSocket->get('http://example.com/redirecting_url', array(), array('redirect' => true));
  147. The *redirect* option can take the following values
  148. * **true** : all redirecting responses will fire a consequent new request
  149. * **integer** : the set value is the maximum number of redirections allowed (after reaching it, the *redirect* value is considered as **false**)
  150. * **false** (default) : no consequent request will be fired
  151. The returned ``$response`` will be the final one, according to the settings.
  152. .. _http-socket-ssl-options:
  153. Handling SSL certificates
  154. -------------------------
  155. When making requests to SSL services HttpSocket will attempt to validate the SSL
  156. certifcate using peer validation. If the certificate fails peer validation or
  157. does not match the hostname being accessed the connection will fail, and an
  158. exception will be thrown. By default HttpSocket will use the mozilla certificate
  159. authority file to verify SSL certificates. You can use the following options to
  160. configure how SSL certificates are handled:
  161. - ``ssl_verify_peer`` Set to false to disable SSL verification. This is
  162. **not recommended**.
  163. - ``ssl_verify_host`` Set to false if you wish to ignore hostname match errors
  164. when validating certificates.
  165. - ``ssl_allow_self_signed`` Set to true to enable self-signed certificates to be
  166. accepted. This requires ``ssl_verify_peer`` to be enabled.
  167. - ``ssl_cafile`` Set to the absolute path of the Certificate Authority file that
  168. you wish to use for verifying SSL certificates.
  169. These options are provided as constructor arguments::
  170. $socket = new HttpSocket(array(
  171. 'ssl_allow_self_signed' => true
  172. ));
  173. Would allow self-signed certificates for all requests made with the created
  174. socket.
  175. .. versionadded:: 2.3
  176. SSL certificate validation was added in 2.3.
  177. Creating a custom response class
  178. --------------------------------
  179. You can create your own response class to use with HttpSocket. You could create
  180. the file ``app/Lib/Network/Http/YourResponse.php`` with the content::
  181. App::uses('HttpResponse', 'Network/Http');
  182. class YourResponse extends HttpResponse {
  183. public function parseResponse($message) {
  184. parent::parseResponse($message);
  185. // Make what you want
  186. }
  187. }
  188. Before your request you'll need to change the responseClass property::
  189. App::uses('HttpSocket', 'Network/Http');
  190. $http = new HttpSocket();
  191. $http->responseClass = 'YourResponse';
  192. .. versionchanged:: 2.3
  193. As of 2.3.0 you should extend ``HttpSocketResponse`` instead. This
  194. avoids a common issue with the HTTP PECL extension.
  195. Downloading the results
  196. -----------------------
  197. HttpSocket has a new method called `setContentResource()`. By setting a resource
  198. with this method, the content will be written to this resource, using
  199. `fwrite()`. To you download a file, you can do::
  200. App::uses('HttpSocket', 'Network/Http');
  201. $http = new HttpSocket();
  202. $f = fopen(TMP . 'bakery.xml', 'w');
  203. $http->setContentResource($f);
  204. $http->get('http://bakery.cakephp.org/comments.rss');
  205. fclose($f);
  206. .. note::
  207. The headers are not included in file, you will only get the body content
  208. written to your resource. To disable saving into the resource, use
  209. ``$http->setContentResource(false)``.
  210. Using authentication
  211. ====================
  212. HttpSocket supports a HTTP Basic and Digest authentication methods out of the
  213. box. You can also create custom authentication objects to support protocols
  214. like OAuth. To use any authentication system you need to configure the
  215. ``HttpSocket`` instance::
  216. App::uses('HttpSocket', 'Network/Http');
  217. $http = new HttpSocket();
  218. $http->configAuth('Basic', 'user', 'password');
  219. The above would configure the ``HttpSocket`` instance to use Basic
  220. authentication using ``user`` and ``password`` as the credentials.
  221. Creating a custom authentication object
  222. ---------------------------------------
  223. You can now create your own authentication method to use with HttpSocket. You
  224. could create the file ``app/Lib/Network/Http/YourMethodAuthentication.php`` with the
  225. content::
  226. class YourMethodAuthentication {
  227. /**
  228. * Authentication
  229. *
  230. * @param HttpSocket $http
  231. * @param array $authInfo
  232. * @return void
  233. */
  234. public static function authentication(HttpSocket $http, &$authInfo) {
  235. // Do something, for example set $http->request['header']['Authentication'] value
  236. }
  237. }
  238. To configure HttpSocket to use your auth configuration, you can use the new
  239. method ``configAuth()``::
  240. $http->configAuth('YourMethod', array('config1' => 'value1', 'config2' => 'value2'));
  241. $http->get('http://secure.your-site.com');
  242. The ``authentication()`` method will be called to append the request headers.
  243. Using a HttpSocket with a proxy
  244. -------------------------------
  245. As part of auth configuration, you can configure proxy authentication. You can
  246. create your customized method to proxy authentication in the same class of
  247. authentication. For example::
  248. class YourMethodAuthentication {
  249. /**
  250. * Authentication
  251. *
  252. * @param HttpSocket $http
  253. * @param array $authInfo
  254. * @return void
  255. */
  256. public static function authentication(HttpSocket $http, &$authInfo) {
  257. // Do something, for example set $http->request['header']['Authentication'] value
  258. }
  259. /**
  260. * Proxy Authentication
  261. *
  262. * @param HttpSocket $http
  263. * @param array $proxyInfo
  264. * @return void
  265. */
  266. public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) {
  267. // Do something, for example set $http->request['header']['Proxy-Authentication'] value
  268. }
  269. }
  270. .. note::
  271. To use a proxy, you must call the ``HttpSocket::configProxy()`` similar to
  272. ``HttpSocket::configAuth()``.
  273. .. meta::
  274. :title lang=en: HttpSocket
  275. :keywords lang=en: array name,array data,query parameter,query string,php class,string query,test type,string data,google,query results,webservices,apis,parameters,cakephp,meth,search results