PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/api/vendor/guzzlehttp/guzzle/docs/http-messages.rst

https://gitlab.com/x33n/respond
ReStructuredText | 483 lines | 346 code | 137 blank | 0 comment | 0 complexity | 37e5a669761894e39e32f6cc6da9ede3 MD5 | raw file
  1. =============================
  2. Request and Response Messages
  3. =============================
  4. Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP
  5. responses. Both requests and responses are referred to as messages.
  6. Headers
  7. =======
  8. Both request and response messages contain HTTP headers.
  9. Complex Headers
  10. ---------------
  11. Some headers contain additional key value pair information. For example, Link
  12. headers contain a link and several key value pairs:
  13. ::
  14. <http://foo.com>; rel="thing"; type="image/jpeg"
  15. Guzzle provides a convenience feature that can be used to parse these types of
  16. headers:
  17. .. code-block:: php
  18. use GuzzleHttp\Message\Request;
  19. $request = new Request('GET', '/', [
  20. 'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
  21. ]);
  22. $parsed = Request::parseHeader($request, 'Link');
  23. var_export($parsed);
  24. Will output:
  25. .. code-block:: php
  26. array (
  27. 0 =>
  28. array (
  29. 0 => '<http:/.../front.jpeg>',
  30. 'rel' => 'front',
  31. 'type' => 'image/jpeg',
  32. ),
  33. )
  34. The result contains a hash of key value pairs. Header values that have no key
  35. (i.e., the link) are indexed numerically while headers parts that form a key
  36. value pair are added as a key value pair.
  37. See :ref:`headers` for information on how the headers of a request and response
  38. can be accessed and modified.
  39. Body
  40. ====
  41. Both request and response messages can contain a body.
  42. You can check to see if a request or response has a body using the
  43. ``getBody()`` method:
  44. .. code-block:: php
  45. $response = GuzzleHttp\get('http://httpbin.org/get');
  46. if ($response->getBody()) {
  47. echo $response->getBody();
  48. // JSON string: { ... }
  49. }
  50. The body used in request and response objects is a
  51. ``GuzzleHttp\Stream\StreamInterface``. This stream is used for both uploading
  52. data and downloading data. Guzzle will, by default, store the body of a message
  53. in a stream that uses PHP temp streams. When the size of the body exceeds
  54. 2 MB, the stream will automatically switch to storing data on disk rather than
  55. in memory (protecting your application from memory exhaustion).
  56. You can change the body used in a request or response using the ``setBody()``
  57. method:
  58. .. code-block:: php
  59. use GuzzleHttp\Stream\Stream;
  60. $request = $client->createRequest('PUT', 'http://httpbin.org/put');
  61. $request->setBody(Stream::factory('foo'));
  62. The easiest way to create a body for a request is using the static
  63. ``GuzzleHttp\Stream\Stream::factory()`` method. This method accepts various
  64. inputs like strings, resources returned from ``fopen()``, and other
  65. ``GuzzleHttp\Stream\StreamInterface`` objects.
  66. The body of a request or response can be cast to a string or you can read and
  67. write bytes off of the stream as needed.
  68. .. code-block:: php
  69. use GuzzleHttp\Stream\Stream;
  70. $request = $client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'testing...']);
  71. echo $request->getBody()->read(4);
  72. // test
  73. echo $request->getBody()->read(4);
  74. // ing.
  75. echo $request->getBody()->read(1024);
  76. // ..
  77. var_export($request->eof());
  78. // true
  79. You can find out more about Guzzle stream objects in :doc:`streams`.
  80. Requests
  81. ========
  82. Requests are sent from a client to a server. Requests include the method to
  83. be applied to a resource, the identifier of the resource, and the protocol
  84. version to use.
  85. Clients are used to create request messages. More precisely, clients use
  86. a ``GuzzleHttp\Message\MessageFactoryInterface`` to create request messages.
  87. You create requests with a client using the ``createRequest()`` method.
  88. .. code-block:: php
  89. // Create a request but don't send it immediately
  90. $request = $client->createRequest('GET', 'http://httpbin.org/get');
  91. Request Methods
  92. ---------------
  93. When creating a request, you are expected to provide the HTTP method you wish
  94. to perform. You can specify any method you'd like, including a custom method
  95. that might not be part of RFC 7231 (like "MOVE").
  96. .. code-block:: php
  97. // Create a request using a completely custom HTTP method
  98. $request = $client->createRequest('MOVE', 'http://httpbin.org/move', ['exceptions' => false]);
  99. echo $request->getMethod();
  100. // MOVE
  101. $response = $client->send($request);
  102. echo $response->getStatusCode();
  103. // 405
  104. You can create and send a request using methods on a client that map to the
  105. HTTP method you wish to use.
  106. :GET: ``$client->get('http://httpbin.org/get', [/** options **/])``
  107. :POST: ``$client->post('http://httpbin.org/post', [/** options **/])``
  108. :HEAD: ``$client->head('http://httpbin.org/get', [/** options **/])``
  109. :PUT: ``$client->put('http://httpbin.org/put', [/** options **/])``
  110. :DELETE: ``$client->delete('http://httpbin.org/delete', [/** options **/])``
  111. :OPTIONS: ``$client->options('http://httpbin.org/get', [/** options **/])``
  112. :PATCH: ``$client->patch('http://httpbin.org/put', [/** options **/])``
  113. .. code-block:: php
  114. $response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);
  115. Request URI
  116. -----------
  117. The resource you are requesting with an HTTP request is identified by the
  118. path of the request, the query string, and the "Host" header of the request.
  119. When creating a request, you can provide the entire resource URI as a URL.
  120. .. code-block:: php
  121. $response = $client->get('http://httbin.org/get?q=foo');
  122. Using the above code, you will send a request that uses ``httpbin.org`` as
  123. the Host header, sends the request over port 80, uses ``/get`` as the path,
  124. and sends ``?q=foo`` as the query string. All of this is parsed automatically
  125. from the provided URI.
  126. Sometimes you don't know what the entire request will be when it is created.
  127. In these cases, you can modify the request as needed before sending it using
  128. the ``createRequest()`` method of the client and methods on the request that
  129. allow you to change it.
  130. .. code-block:: php
  131. $request = $client->createRequest('GET', 'http://httbin.org');
  132. You can change the path of the request using ``setPath()``:
  133. .. code-block:: php
  134. $request->setPath('/get');
  135. echo $request->getPath();
  136. // /get
  137. echo $request->getUrl();
  138. // http://httpbin.com/get
  139. Scheme
  140. ~~~~~~
  141. The `scheme <http://tools.ietf.org/html/rfc3986#section-3.1>`_ of a request
  142. specifies the protocol to use when sending the request. When using Guzzle, the
  143. scheme can be set to "http" or "https".
  144. You can change the scheme of the request using the ``setScheme()`` method:
  145. .. code-block:: php
  146. $request = $client->createRequest('GET', 'http://httbin.org');
  147. $request->setScheme('https');
  148. echo $request->getScheme();
  149. // https
  150. echo $request->getUrl();
  151. // https://httpbin.com/get
  152. Port
  153. ~~~~
  154. No port is necessary when using the "http" or "https" schemes, but you can
  155. override the port using ``setPort()``. If you need to modify the port used with
  156. the specified scheme from the default setting, then you must use the
  157. ``setPort()`` method.
  158. .. code-block:: php
  159. $request = $client->createRequest('GET', 'http://httbin.org');
  160. $request->setPort(8080);
  161. echo $request->getPort();
  162. // 8080
  163. echo $request->getUrl();
  164. // https://httpbin.com:8080/get
  165. // Set the port back to the default value for the scheme
  166. $request->setPort(443);
  167. echo $request->getUrl();
  168. // https://httpbin.com/get
  169. Query string
  170. ~~~~~~~~~~~~
  171. You can get the query string of the request using the ``getQuery()`` method.
  172. This method returns a ``GuzzleHttp\Query`` object. A Query object can be
  173. accessed like a PHP array, iterated in a foreach statement like a PHP array,
  174. and cast to a string.
  175. .. code-block:: php
  176. $request = $client->createRequest('GET', 'http://httbin.org');
  177. $query = $request->getQuery();
  178. $query['foo'] = 'bar';
  179. $query['baz'] = 'bam';
  180. $query['bam'] = ['test' => 'abc'];
  181. echo $request->getQuery();
  182. // foo=bar&baz=bam&bam%5Btest%5D=abc
  183. echo $request->getQuery()['foo'];
  184. // bar
  185. echo $request->getQuery()->get('foo');
  186. // bar
  187. echo $request->getQuery()->get('foo');
  188. // bar
  189. var_export($request->getQuery()['bam']);
  190. // array('test' => 'abc')
  191. foreach ($query as $key => $value) {
  192. var_export($value);
  193. }
  194. echo $request->getUrl();
  195. // https://httpbin.com/get?foo=bar&baz=bam&bam%5Btest%5D=abc
  196. Query Aggregators
  197. ^^^^^^^^^^^^^^^^^
  198. Query objects can store scalar values or arrays of values. When an array of
  199. values is added to a query object, the query object uses a query aggregator to
  200. convert the complex structure into a string. Query objects will use
  201. `PHP style query strings <http://www.php.net/http_build_query>`_ when complex
  202. query string parameters are converted to a string. You can customize how
  203. complex query string parameters are aggregated using the ``setAggregator()``
  204. method of a query string object.
  205. .. code-block:: php
  206. $query->setAggregator($query::duplicateAggregator());
  207. In the above example, we've changed the query object to use the
  208. "duplicateAggregator". This aggregator will allow duplicate entries to appear
  209. in a query string rather than appending "[n]" to each value. So if you had a
  210. query string with ``['a' => ['b', 'c']]``, the duplicate aggregator would
  211. convert this to "a=b&a=c" while the default aggregator would convert this to
  212. "a[0]=b&a[1]=c" (with urlencoded brackets).
  213. The ``setAggregator()`` method accepts a ``callable`` which is used to convert
  214. a deeply nested array of query string variables into a flattened array of key
  215. value pairs. The callable accepts an array of query data and returns a
  216. flattened array of key value pairs where each value is an array of strings.
  217. You can use the ``GuzzleHttp\Query::walkQuery()`` static function to easily
  218. create custom query aggregators.
  219. Host
  220. ~~~~
  221. You can change the host header of the request in a predictable way using the
  222. ``setHost()`` method of a request:
  223. .. code-block:: php
  224. $request->setHost('www.google.com');
  225. echo $request->getHost();
  226. // www.google.com
  227. echo $request->getUrl();
  228. // https://www.google.com/get?foo=bar&baz=bam
  229. .. note::
  230. The Host header can also be changed by modifying the Host header of a
  231. request directly, but modifying the Host header directly could result in
  232. sending a request to a different Host than what is specified in the Host
  233. header (sometimes this is actually the desired behavior).
  234. Resource
  235. ~~~~~~~~
  236. You can use the ``getResource()`` method of a request to return the path and
  237. query string of a request in a single string.
  238. .. code-block:: php
  239. $request = $client->createRequest('GET', 'http://httpbin.org/get?baz=bar');
  240. echo $request->getResource();
  241. // /get?baz=bar
  242. Request Config
  243. --------------
  244. Request messages contain a configuration collection that can be used by
  245. event listeners and HTTP handlers to modify how a request behaves or is
  246. transferred over the wire. For example, many of the request options that are
  247. specified when creating a request are actually set as config options that are
  248. only acted upon by handlers and listeners when the request is sent.
  249. You can get access to the request's config object using the ``getConfig()``
  250. method of a request.
  251. .. code-block:: php
  252. $request = $client->createRequest('GET', '/');
  253. $config = $request->getConfig();
  254. The config object is a ``GuzzleHttp\Collection`` object that acts like
  255. an associative array. You can grab values from the collection using array like
  256. access. You can also modify and remove values using array like access.
  257. .. code-block:: php
  258. $config['foo'] = 'bar';
  259. echo $config['foo'];
  260. // bar
  261. var_export(isset($config['foo']));
  262. // true
  263. unset($config['foo']);
  264. var_export(isset($config['foo']));
  265. // false
  266. var_export($config['foo']);
  267. // NULL
  268. HTTP handlers and event listeners can expose additional customization options
  269. through request config settings. For example, in order to specify custom cURL
  270. options to the cURL handler, you need to specify an associative array in the
  271. ``curl`` ``config`` request option.
  272. .. code-block:: php
  273. $client->get('/', [
  274. 'config' => [
  275. 'curl' => [
  276. CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
  277. CURLOPT_USERPWD => 'username:password'
  278. ]
  279. ]
  280. ]);
  281. Consult the HTTP handlers and event listeners you are using to see if they
  282. allow customization through request configuration options.
  283. Event Emitter
  284. -------------
  285. Request objects implement ``GuzzleHttp\Event\HasEmitterInterface``, so they
  286. have a method called ``getEmitter()`` that can be used to get an event emitter
  287. used by the request. Any listener or subscriber attached to a request will only
  288. be triggered for the lifecycle events of a specific request. Conversely, adding
  289. an event listener or subscriber to a client will listen to all lifecycle events
  290. of all requests created by the client.
  291. See :doc:`events` for more information.
  292. Responses
  293. =========
  294. Responses are the HTTP messages a client receives from a server after sending
  295. an HTTP request message.
  296. Start-Line
  297. ----------
  298. The start-line of a response contains the protocol and protocol version,
  299. status code, and reason phrase.
  300. .. code-block:: php
  301. $response = GuzzleHttp\get('http://httpbin.org/get');
  302. echo $response->getStatusCode();
  303. // 200
  304. echo $response->getReasonPhrase();
  305. // OK
  306. echo $response->getProtocolVersion();
  307. // 1.1
  308. Body
  309. ----
  310. As described earlier, you can get the body of a response using the
  311. ``getBody()`` method.
  312. .. code-block:: php
  313. if ($body = $response->getBody()) {
  314. echo $body;
  315. // Cast to a string: { ... }
  316. $body->seek(0);
  317. // Rewind the body
  318. $body->read(1024);
  319. // Read bytes of the body
  320. }
  321. When working with JSON responses, you can use the ``json()`` method of a
  322. response:
  323. .. code-block:: php
  324. $json = $response->json();
  325. .. note::
  326. Guzzle uses the ``json_decode()`` method of PHP and uses arrays rather than
  327. ``stdClass`` objects for objects.
  328. You can use the ``xml()`` method when working with XML data.
  329. .. code-block:: php
  330. $xml = $response->xml();
  331. .. note::
  332. Guzzle uses the ``SimpleXMLElement`` objects when converting response
  333. bodies to XML.
  334. Effective URL
  335. -------------
  336. The URL that was ultimately accessed that returned a response can be accessed
  337. using the ``getEffectiveUrl()`` method of a response. This method will return
  338. the URL of a request or the URL of the last redirected URL if any redirects
  339. occurred while transferring a request.
  340. .. code-block:: php
  341. $response = GuzzleHttp\get('http://httpbin.org/get');
  342. echo $response->getEffectiveUrl();
  343. // http://httpbin.org/get
  344. $response = GuzzleHttp\get('http://httpbin.org/redirect-to?url=http://www.google.com');
  345. echo $response->getEffectiveUrl();
  346. // http://www.google.com