Zend_Http_Client.xml 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <sect1 id="zend.http.client">
  2. <title>Zend_Http_Client - Введение</title>
  3. <sect2 id="zend.http.client.introduction">
  4. <title>Введение</title>
  5. <para>
  6. Zend_Http_Client предоставляет простой интерфейс для выполнения
  7. HTTP-запросов. Zend_Http_Client поддерживает как большинство простых
  8. возможностей, ожидаемых от любого HTTP-клиента, так и более сложные
  9. функции, такие, как HTTP-аутентификация и выгрузка файлов. При
  10. успешно выполненных запросах (и большинстве неуспешно выполненных)
  11. возвращается объект Zend_Http_Response, который предоставляет доступ
  12. к заголовкам и телу ответа (см. <xref linkend="zend.http.response" />).
  13. <!--
  14. Zend_Http_Client provides an easy interface for preforming Hyper-Text
  15. Transfer Protocol (HTTP) requests. Zend_Http_Client supports most simple
  16. features expected from an HTTP client, as well as some more complex
  17. features such as HTTP authentication and file uploads. Successful
  18. requests (and most unsuccessful ones too) return a Zend_Http_Response
  19. object, which provides access to the response's headers and body (see
  20. <xref linkend="zend.http.response" />).
  21. -->
  22. </para>
  23. <para>
  24. Конструктор класса опционально принимает URL (может быть строкой или
  25. объектом Zend_Uri_Http) и массив конфирурационных параметров. Оба
  26. параметра могут быть опущены и установлены позднее через методы
  27. <code>setUri()</code> и <code>setConfig()</code>.
  28. <!--
  29. The class constructor optionally accepts a URL as it's first parameter
  30. (can be either a string or a Zend_Uri_Http object), and an optional
  31. array of configuration parameters. Both can be left out,
  32. and set later using the setUri() and setConfig() methods.
  33. -->
  34. <example>
  35. <title>Инстанцирование объекта Zend_Http_Client<!--Instantiating a Zend_Http_Client object--></title>
  36. <programlisting language="php">
  37. <![CDATA[<?php
  38. require_once 'Zend/Http/Client.php';
  39. $client = new Zend_Http_Client('http://example.org', array(
  40. 'maxredirects' => 0,
  41. 'timeout' => 30));
  42. // Этот код делает то же самое:
  43. $client = new Zend_Http_Client();
  44. $client->setUri('http://example.org');
  45. $client->setConfig(array(
  46. 'maxredirects' => 0,
  47. 'timeout' => 30));
  48. ?>]]></programlisting>
  49. </example>
  50. </para>
  51. </sect2>
  52. <sect2 id="zend.http.client.configuration">
  53. <title>Параметры конфигурации<!--Configuration Parameters--></title>
  54. <para>
  55. Конструктор и метод <code>setConfig()</code> принимают ассоциативный
  56. массив параметров конфигурации. Установка этих параметров является
  57. опциональной, поскольку все они имеют значения по умолчанию.
  58. <!--
  59. The constructor and setConfig() method accept an associative array
  60. of configuration parameters. Setting these parameters is optional,
  61. as they all have default values.
  62. -->
  63. <table>
  64. <title>Параметры конфигурации Zend_Http_Client<!--Zend_Http_Client configuration parameters--></title>
  65. <tgroup cols="4">
  66. <thead>
  67. <row>
  68. <entry>Параметр</entry>
  69. <entry>Описание</entry>
  70. <entry>Тип</entry>
  71. <entry>Значение по умолчанию</entry>
  72. </row>
  73. </thead>
  74. <tbody>
  75. <row>
  76. <entry>maxredirects</entry>
  77. <entry>
  78. Максимальное количество последующих
  79. перенаправлений (0 = ни одного перенаправления)
  80. <!--
  81. Maximum number of redirections to follow (0 = none)
  82. -->
  83. </entry>
  84. <entry>integer</entry>
  85. <entry>5</entry>
  86. </row>
  87. <row>
  88. <entry>strictredirects</entry>
  89. <entry>
  90. Строгое следование спецификации RFC при
  91. перенаправлениях (см. <xref linkend="zend.http.client.redirections" />)
  92. <!--
  93. Whether to strictly follow the RFC when redirecting (see <xref linkend="zend.http.client.redirections" />)
  94. -->
  95. </entry>
  96. <entry>boolean</entry>
  97. <entry>false</entry>
  98. </row>
  99. <row>
  100. <entry>useragent</entry>
  101. <entry>
  102. Идентификатор агента пользователя (отправляется
  103. в заголовке запроса)
  104. <!--
  105. User agent identifier string (sent in request headers)
  106. -->
  107. </entry>
  108. <entry>string</entry>
  109. <entry>'Zend_Http_Client'</entry>
  110. </row>
  111. <row>
  112. <entry>timeout</entry>
  113. <entry>
  114. Таймаут соединения в секундах
  115. <!--
  116. Connection timeout (seconds)
  117. -->
  118. </entry>
  119. <entry>integer</entry>
  120. <entry>10</entry>
  121. </row>
  122. <row>
  123. <entry>httpversion</entry>
  124. <entry>
  125. Версия протокола HTTP
  126. <!--
  127. HTTP protocol version
  128. -->
  129. </entry>
  130. <entry>float (1.1 or 1.0)</entry>
  131. <entry>1.1</entry>
  132. </row>
  133. <row>
  134. <entry>adapter</entry>
  135. <entry>
  136. Используемый класс адаптера соединения
  137. (см. <xref linkend="zend.http.client.adapters" />)
  138. <!--
  139. Connection adapter class to use (see <xref linkend="zend.http.client.adapters" />)
  140. -->
  141. </entry>
  142. <entry>mixed</entry>
  143. <entry>'Zend_Http_Client_Adapter_Socket'</entry>
  144. </row>
  145. <row>
  146. <entry>keepalive</entry>
  147. <entry>
  148. Включение поддержки соединения keep-alive с
  149. сервером. Может быть полезно и повышает
  150. поизводительность, если выполняется несколько
  151. последовательных запросов к одному и тому же
  152. серверу.
  153. <!--
  154. Whether to enable keep-alive connections with the server. Useful and might improve performance if several consecutive requests to the same server are performned.
  155. -->
  156. </entry>
  157. <entry>boolean</entry>
  158. <entry>false</entry>
  159. </row>
  160. </tbody>
  161. </tgroup>
  162. </table>
  163. </para>
  164. </sect2>
  165. <sect2 id="zend.http.client.basic-requests">
  166. <title>Выполнение базовых HTTP-запросов<!--Performing Basic HTTP Requests--></title>
  167. <para>
  168. Выполнение простых HTTP-запросов с использованием метода
  169. <code>request()</code> довольно простое, и редко требуется больше
  170. кода, чем в эти три строчки:
  171. <!--
  172. Performing simple HTTP requests is very easily done using the
  173. request() method, and rarely needs more than three lines of code:
  174. -->
  175. <example>
  176. <title>Выполнение простого запроса GET<!--Preforming a Simple GET Request--></title>
  177. <programlisting language="php">
  178. <![CDATA[<?php
  179. require_once 'Zend/Http/Client.php';
  180. $client = new Zend_Http_Client('http://example.org');
  181. $response = $client->request();
  182. ?>]]></programlisting>
  183. </example>
  184. Метод <code>request()</code> принимает один необязательный параметр
  185. - метод запроса. Это могут быть методы GET, POST, PUT, HEAD, DELETE,
  186. TRACE, OPTIONS или CONNECT, определенные в протоколе HTTP.
  187. <!--
  188. The request() method takes one optional parameter - the request method.
  189. This can be either GET, POST, PUT, HEAD, DELETE, TRACE, OPTIONS or
  190. CONNECT as defined by the HTTP protocol
  191. -->
  192. <footnote>
  193. <para>
  194. См. RFC 2616 - <ulink url="http://www.w3.org/Protocols/rfc2616/rfc2616.html" />.
  195. </para>
  196. </footnote>.
  197. Для удобства все они определены как константы класса:
  198. Zend_Http_Request::GET, Zend_Http_Request::POST и т.д.
  199. <!--
  200. For convenience, these are all defined as class constants:
  201. Zend_Http_Request::GET, Zend_Http_Request::POST and so on.
  202. -->
  203. </para>
  204. <para>
  205. Если метод запроса не был указан, то используемый метод определяется
  206. последним вызовом <code>setMethod()</code>. Если
  207. <code>setMethod()</code> не был вызван, то по умолчанию используется
  208. метод GET (см. пример выше).
  209. <!--
  210. If no method is specified, the method set by the last setMethod()
  211. call is used. If setMethod() was never called, the default request
  212. method is GET (see the above example).
  213. -->
  214. <example>
  215. <title>Использование методов запроса, отличных от GET<!--Using Request Methods Other Than GET--></title>
  216. <programlisting language="php">
  217. <![CDATA[<?php
  218. // Выполнение запроса POST
  219. $response = $client->request('POST');
  220. // Еще один способ сделать то же самое:
  221. $client->setMethod(Zend_Http_Client::POST);
  222. $response = $client->request();
  223. ?>]]></programlisting>
  224. </example>
  225. </para>
  226. </sect2>
  227. <sect2 id="zend.http.client.parameters">
  228. <title>Добавление параметров GET и POST<!--Adding GET and POST parameters--></title>
  229. <para>
  230. Добавление параметров GET в HTTP-запрос довольно простое, это может
  231. быть сделано посредством определения параметров как часть URL или с
  232. использованием метода <code>setParameterGet()</code>. Этот метод
  233. принимает имя параметра GET и его значение первый и второй аргументы
  234. соответственно. Метод <code>setParameterGet()</code>
  235. может также принимать ассоциативный массив пар имя => значение, что
  236. удобно, если нужно установить несколько параметров GET.
  237. <!--
  238. Adding GET parameters to an HTTP request is quite simple, and can
  239. be done either by specifying them as part of the URL, or by using
  240. the setParameterGet() method.
  241. This method takes the GET parameter's name as it's first parameter,
  242. and the GET parameter's value as it's second parameter.
  243. For convenience, the setParameterGet() method can also accept a
  244. single associative array of name => value GET variables - which may
  245. be more comfortable when several GET parameters need to be set.
  246. -->
  247. <example>
  248. <title>Установка параметров GET<!--Setting GET Parameters--></title>
  249. <programlisting language="php">
  250. <![CDATA[<?php
  251. // Установка параметра GET с использованием метода setParameterGet
  252. $client->setParameterGet('knight', 'lancelot');
  253. // Эвивалентный код с установкой через URL:
  254. $client->setUri('http://example.com/index.php?knight=lancelot');
  255. // Добавление нескольких параметров в одном вызове
  256. $client->setParameterGet(array(
  257. 'first_name' => 'Bender',
  258. 'middle_name' => 'Bending'
  259. 'made_in' => 'Mexico',
  260. ));
  261. ?>]]></programlisting>
  262. </example>
  263. </para>
  264. <para>
  265. В то время как параметры GET могут отправляться с любыми методами
  266. запроса, параметры POST могут отправляться только в теле запроса
  267. POST. Добавление параметров POST к запросу очень похоже на
  268. добавление параметров GET и выполняется через метод
  269. <code>setParameterPost()</code>.
  270. <!--
  271. While GET parameters can be sent with every request method, POST
  272. parameters are only sent in the body of POST requests. Adding POST
  273. parameters to a request is very similar to adding GET parameters,
  274. and can be done with the setParameterPost() method, which is
  275. similar to the setParameterGet() method in structure.
  276. -->
  277. <example>
  278. <title>Установка параметров POST<!--Setting POST Parameters--></title>
  279. <programlisting language="php">
  280. <![CDATA[<?php
  281. // Установка параметра POST
  282. $client->setParameterPost('language', 'fr');
  283. // Установка нескольких параметров POST,
  284. // один из них - с несколькими значениями
  285. $client->setParameterPost(array(
  286. 'language' => 'es',
  287. 'country' => 'ar',
  288. 'selection' => array(45, 32, 80)
  289. ));
  290. ?>]]></programlisting>
  291. </example>
  292. Заметьте, что отправляя запрос POST, вы можете установить как
  293. параметры POST, так и параметры GET. С другой стороны, хотя
  294. установка параметров POST для не-POST запросов не вызывает ошибки,
  295. она не имеет практического смысла. Если запрос не производится по
  296. методу POST, то параметры POST просто игнорируются.
  297. <!--
  298. Note that when sending POST requests, you can set both GET and
  299. POST parameters. On the other hand, while setting POST parameters
  300. for a non-POST request will not trigger and error, it is useless.
  301. Unless the request is a POST request, POST parameters are simply
  302. ignored.
  303. -->
  304. </para>
  305. </sect2>
  306. <sect2 id="zend.http.client.accessing_last">
  307. <title>Получение последних запроса и ответа<!--Accessing Last Request and Response--></title>
  308. <para>
  309. Zend_Http_Client предоставляет методы для получения последнего
  310. отправленного запроса и последнего ответа, полученного через
  311. объект клиента. Метод
  312. <code>Zend_Http_Client->getLastRequest()</code> не требует
  313. параметров и возвращает последний HTTP-запрос, отправленный
  314. через объект клиента, в виде строки. Аналогично,
  315. <code>Zend_Http_Client->getLastResponse()</code> возвращает
  316. последний HTTP-ответ, полученный через объект клиента, в виде
  317. объекта <link linkend="zend.http.response">Zend_Http_Response</link>.
  318. <!--
  319. Zend_Http_Client provides methods of accessing the last request
  320. sent and last response received by the client object.
  321. <code>Zend_Http_Client->getLastRequest()</code> takes no parameters
  322. and returns the last HTTP request sent by the client as a string.
  323. Similarly, <code>Zend_Http_Client->getLastResponse()</code> returns
  324. the last HTTP response received by the client as a
  325. <link linkend="zend.http.response">Zend_Http_Response</link> object.
  326. -->
  327. </para>
  328. </sect2>
  329. </sect1>
  330. <!--
  331. vim:se ts=4 sw=4 et:
  332. -->