blob: a9ca4b0d0f7c991426fcaae018cf313516e1ad87 [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001:mod:`http.client` --- HTTP protocol client
2===========================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Georg Brandl24420152008-05-26 16:32:26 +00004.. module:: http.client
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: HTTP and HTTPS protocol client (requires sockets).
6
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007**Source code:** :source:`Lib/http/client.py`
Georg Brandl116aa622007-08-15 14:28:22 +00008
9.. index::
10 pair: HTTP; protocol
Georg Brandl24420152008-05-26 16:32:26 +000011 single: HTTP; http.client (standard module)
Georg Brandl116aa622007-08-15 14:28:22 +000012
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000013.. index:: module: urllib.request
Georg Brandl116aa622007-08-15 14:28:22 +000014
Raymond Hettinger469271d2011-01-27 20:38:46 +000015--------------
16
Georg Brandl116aa622007-08-15 14:28:22 +000017This module defines classes which implement the client side of the HTTP and
Senthil Kumaranaca8fd72008-06-23 04:41:59 +000018HTTPS protocols. It is normally not used directly --- the module
Georg Brandl0f7ede42008-06-23 11:23:31 +000019:mod:`urllib.request` uses it to handle URLs that use HTTP and HTTPS.
Georg Brandl116aa622007-08-15 14:28:22 +000020
Benjamin Peterson6de708f2015-04-20 18:18:14 -040021.. seealso::
22
Georg Brandl5d941342016-02-26 19:37:12 +010023 The `Requests package <https://requests.readthedocs.org/>`_
Martin Panterfe289c02016-05-28 02:20:39 +000024 is recommended for a higher-level HTTP client interface.
Benjamin Peterson6de708f2015-04-20 18:18:14 -040025
Georg Brandl116aa622007-08-15 14:28:22 +000026.. note::
27
Antoine Pitrou1ab19ca2010-10-13 10:39:21 +000028 HTTPS support is only available if Python was compiled with SSL support
29 (through the :mod:`ssl` module).
Georg Brandl116aa622007-08-15 14:28:22 +000030
Georg Brandl116aa622007-08-15 14:28:22 +000031The module provides the following classes:
32
33
Senthil Kumaran052ddb02013-03-18 14:11:41 -070034.. class:: HTTPConnection(host, port=None[, timeout], \
Ezio Melottie0add762012-09-14 06:32:35 +030035 source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000036
37 An :class:`HTTPConnection` instance represents one transaction with an HTTP
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000038 server. It should be instantiated passing it a host and optional port
39 number. If no port number is passed, the port is extracted from the host
40 string if it has the form ``host:port``, else the default HTTP port (80) is
Antoine Pitrou988dbd72010-12-17 17:35:56 +000041 used. If the optional *timeout* parameter is given, blocking
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000042 operations (like connection attempts) will timeout after that many seconds
Georg Brandlf78e02b2008-06-10 17:40:04 +000043 (if it is not given, the global default timeout setting is used).
Raymond Hettinger519c3082011-01-30 00:39:00 +000044 The optional *source_address* parameter may be a tuple of a (host, port)
Gregory P. Smithb4066372010-01-03 03:28:29 +000045 to use as the source address the HTTP connection is made from.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47 For example, the following calls all create instances that connect to the server
48 at the same host and port::
49
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010050 >>> h1 = http.client.HTTPConnection('www.python.org')
51 >>> h2 = http.client.HTTPConnection('www.python.org:80')
52 >>> h3 = http.client.HTTPConnection('www.python.org', 80)
53 >>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)
Georg Brandl116aa622007-08-15 14:28:22 +000054
Gregory P. Smithb4066372010-01-03 03:28:29 +000055 .. versionchanged:: 3.2
56 *source_address* was added.
Georg Brandl116aa622007-08-15 14:28:22 +000057
Senthil Kumaranaced69f2013-03-19 01:22:56 -070058 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -050059 The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
60 not longer supported.
Gregory P. Smithb4066372010-01-03 03:28:29 +000061
Antoine Pitrou988dbd72010-12-17 17:35:56 +000062
Ezio Melottie0add762012-09-14 06:32:35 +030063.. class:: HTTPSConnection(host, port=None, key_file=None, \
Senthil Kumaran052ddb02013-03-18 14:11:41 -070064 cert_file=None[, timeout], \
Ezio Melottie0add762012-09-14 06:32:35 +030065 source_address=None, *, context=None, \
66 check_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 A subclass of :class:`HTTPConnection` that uses SSL for communication with
Antoine Pitrou803e6d62010-10-13 10:36:15 +000069 secure servers. Default port is ``443``. If *context* is specified, it
70 must be a :class:`ssl.SSLContext` instance describing the various SSL
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010071 options.
Georg Brandl116aa622007-08-15 14:28:22 +000072
Antoine Pitrou803e6d62010-10-13 10:36:15 +000073 *key_file* and *cert_file* are deprecated, please use
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010074 :meth:`ssl.SSLContext.load_cert_chain` instead, or let
75 :func:`ssl.create_default_context` select the system's trusted CA
Benjamin Petersona090f012014-12-07 13:18:25 -050076 certificates for you. The *check_hostname* parameter is also deprecated; the
Benjamin Petersone3b743c2014-12-07 17:26:38 -050077 :attr:`ssl.SSLContext.check_hostname` attribute of *context* should be used
Benjamin Petersona090f012014-12-07 13:18:25 -050078 instead.
Antoine Pitrou803e6d62010-10-13 10:36:15 +000079
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010080 Please read :ref:`ssl-security` for more information on best practices.
81
Gregory P. Smithb4066372010-01-03 03:28:29 +000082 .. versionchanged:: 3.2
Antoine Pitrou803e6d62010-10-13 10:36:15 +000083 *source_address*, *context* and *check_hostname* were added.
Gregory P. Smithb4066372010-01-03 03:28:29 +000084
Antoine Pitroud5323212010-10-22 18:19:07 +000085 .. versionchanged:: 3.2
86 This class now supports HTTPS virtual hosts if possible (that is,
87 if :data:`ssl.HAS_SNI` is true).
88
Senthil Kumaranaced69f2013-03-19 01:22:56 -070089 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -050090 The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
91 no longer supported.
Georg Brandl116aa622007-08-15 14:28:22 +000092
Benjamin Peterson4ffb0752014-11-03 14:29:33 -050093 .. versionchanged:: 3.4.3
94 This class now performs all the necessary certificate and hostname checks
95 by default. To revert to the previous, unverified, behavior
96 :func:`ssl._create_unverified_context` can be passed to the *context*
97 parameter.
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
Senthil Kumaran052ddb02013-03-18 14:11:41 -0700100.. class:: HTTPResponse(sock, debuglevel=0, method=None, url=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Jeremy Hylton1052f892009-03-31 14:40:19 +0000102 Class whose instances are returned upon successful connection. Not
103 instantiated directly by user.
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Senthil Kumaranaced69f2013-03-19 01:22:56 -0700105 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -0500106 The *strict* parameter was removed. HTTP 0.9 style "Simple Responses" are
107 no longer supported.
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000108
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110The following exceptions are raised as appropriate:
111
112
113.. exception:: HTTPException
114
115 The base class of the other exceptions in this module. It is a subclass of
116 :exc:`Exception`.
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119.. exception:: NotConnected
120
121 A subclass of :exc:`HTTPException`.
122
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124.. exception:: InvalidURL
125
126 A subclass of :exc:`HTTPException`, raised if a port is given and is either
127 non-numeric or empty.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. exception:: UnknownProtocol
131
132 A subclass of :exc:`HTTPException`.
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135.. exception:: UnknownTransferEncoding
136
137 A subclass of :exc:`HTTPException`.
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140.. exception:: UnimplementedFileMode
141
142 A subclass of :exc:`HTTPException`.
143
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145.. exception:: IncompleteRead
146
147 A subclass of :exc:`HTTPException`.
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150.. exception:: ImproperConnectionState
151
152 A subclass of :exc:`HTTPException`.
153
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155.. exception:: CannotSendRequest
156
157 A subclass of :exc:`ImproperConnectionState`.
158
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160.. exception:: CannotSendHeader
161
162 A subclass of :exc:`ImproperConnectionState`.
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. exception:: ResponseNotReady
166
167 A subclass of :exc:`ImproperConnectionState`.
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170.. exception:: BadStatusLine
171
172 A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP
173 status code that we don't understand.
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Berker Peksagbabc6882015-02-20 09:39:38 +0200176.. exception:: LineTooLong
177
178 A subclass of :exc:`HTTPException`. Raised if an excessively long line
179 is received in the HTTP protocol from the server.
180
181
R David Murraycae7bdb2015-04-05 19:26:29 -0400182.. exception:: RemoteDisconnected
183
184 A subclass of :exc:`ConnectionResetError` and :exc:`BadStatusLine`. Raised
185 by :meth:`HTTPConnection.getresponse` when the attempt to read the response
186 results in no data read from the connection, indicating that the remote end
187 has closed the connection.
188
189 .. versionadded:: 3.5
190 Previously, :exc:`BadStatusLine`\ ``('')`` was raised.
191
192
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100193The constants defined in this module are:
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195.. data:: HTTP_PORT
196
197 The default port for the HTTP protocol (always ``80``).
198
199
200.. data:: HTTPS_PORT
201
202 The default port for the HTTPS protocol (always ``443``).
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204.. data:: responses
205
206 This dictionary maps the HTTP 1.1 status codes to the W3C names.
207
Georg Brandl24420152008-05-26 16:32:26 +0000208 Example: ``http.client.responses[http.client.NOT_FOUND]`` is ``'Not Found'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Berker Peksagcb18b952015-01-20 06:30:46 +0200210See :ref:`http-status-codes` for a list of HTTP status codes that are
211available in this module as constants.
212
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214.. _httpconnection-objects:
215
216HTTPConnection Objects
217----------------------
218
219:class:`HTTPConnection` instances have the following methods:
220
221
Georg Brandl036490d2009-05-17 13:00:36 +0000222.. method:: HTTPConnection.request(method, url, body=None, headers={})
Georg Brandl116aa622007-08-15 14:28:22 +0000223
Jeremy Hylton236654b2009-03-27 20:24:34 +0000224 This will send a request to the server using the HTTP request
R David Murraybeed8402015-03-22 15:18:23 -0400225 method *method* and the selector *url*.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
R David Murraybeed8402015-03-22 15:18:23 -0400227 If *body* is specified, the specified data is sent after the headers are
228 finished. It may be a string, a :term:`bytes-like object`, an open
229 :term:`file object`, or an iterable of :term:`bytes-like object`\s. If
Martin Panter540f0452016-08-10 05:25:16 +0000230 *body* is a string, it is encoded as ISO-8859-1, the default for HTTP. If
R David Murraybeed8402015-03-22 15:18:23 -0400231 it is a bytes-like object the bytes are sent as is. If it is a :term:`file
232 object`, the contents of the file is sent; this file object should support
233 at least the ``read()`` method. If the file object has a ``mode``
234 attribute, the data returned by the ``read()`` method will be encoded as
Martin Panter540f0452016-08-10 05:25:16 +0000235 ISO-8859-1 unless the ``mode`` attribute contains the substring ``b``,
R David Murraybeed8402015-03-22 15:18:23 -0400236 otherwise the data returned by ``read()`` is sent as is. If *body* is an
237 iterable, the elements of the iterable are sent as is until the iterable is
238 exhausted.
Jeremy Hylton236654b2009-03-27 20:24:34 +0000239
240 The *headers* argument should be a mapping of extra HTTP
241 headers to send with the request.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
R David Murraybeed8402015-03-22 15:18:23 -0400243 If *headers* does not contain a Content-Length item, one is added
244 automatically if possible. If *body* is ``None``, the Content-Length header
245 is set to ``0`` for methods that expect a body (``PUT``, ``POST``, and
246 ``PATCH``). If *body* is a string or bytes object, the Content-Length
247 header is set to its length. If *body* is a :term:`file object` and it
248 works to call :func:`~os.fstat` on the result of its ``fileno()`` method,
249 then the Content-Length header is set to the ``st_size`` reported by the
250 ``fstat`` call. Otherwise no Content-Length header is added.
251
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000252 .. versionadded:: 3.2
Georg Brandl09a7df82010-12-19 12:33:52 +0000253 *body* can now be an iterable.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000254
Georg Brandl116aa622007-08-15 14:28:22 +0000255.. method:: HTTPConnection.getresponse()
256
257 Should be called after a request is sent to get the response from the server.
258 Returns an :class:`HTTPResponse` instance.
259
260 .. note::
261
262 Note that you must have read the whole response before you can send a new
263 request to the server.
264
R David Murraycae7bdb2015-04-05 19:26:29 -0400265 .. versionchanged:: 3.5
266 If a :exc:`ConnectionError` or subclass is raised, the
267 :class:`HTTPConnection` object will be ready to reconnect when
268 a new request is sent.
269
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271.. method:: HTTPConnection.set_debuglevel(level)
272
R. David Murrayd89bc3f2010-12-15 02:19:14 +0000273 Set the debugging level. The default debug level is ``0``, meaning no
274 debugging output is printed. Any value greater than ``0`` will cause all
275 currently defined debug output to be printed to stdout. The ``debuglevel``
276 is passed to any new :class:`HTTPResponse` objects that are created.
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Mark Dickinson574b1d62009-10-01 20:20:09 +0000278 .. versionadded:: 3.1
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000279
Georg Brandl67b21b72010-08-17 15:07:14 +0000280
Senthil Kumaran7e5229c2009-12-20 07:31:21 +0000281.. method:: HTTPConnection.set_tunnel(host, port=None, headers=None)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000282
Benjamin Petersona48d9ea2014-03-16 15:55:39 -0500283 Set the host and the port for HTTP Connect Tunnelling. This allows running
284 the connection through a proxy server.
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000285
Benjamin Petersona48d9ea2014-03-16 15:55:39 -0500286 The host and port arguments specify the endpoint of the tunneled connection
287 (i.e. the address included in the CONNECT request, *not* the address of the
288 proxy server).
289
290 The headers argument should be a mapping of extra HTTP headers to send with
291 the CONNECT request.
292
293 For example, to tunnel through a HTTPS proxy server running locally on port
294 8080, we would pass the address of the proxy to the :class:`HTTPSConnection`
295 constructor, and the address of the host that we eventually want to reach to
296 the :meth:`~HTTPConnection.set_tunnel` method::
297
298 >>> import http.client
299 >>> conn = http.client.HTTPSConnection("localhost", 8080)
300 >>> conn.set_tunnel("www.python.org")
301 >>> conn.request("HEAD","/index.html")
Senthil Kumaran7e5229c2009-12-20 07:31:21 +0000302
Senthil Kumaran2e910fd2009-07-25 04:27:38 +0000303 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandl67b21b72010-08-17 15:07:14 +0000305
Georg Brandl116aa622007-08-15 14:28:22 +0000306.. method:: HTTPConnection.connect()
307
R David Murraycae7bdb2015-04-05 19:26:29 -0400308 Connect to the server specified when the object was created. By default,
309 this is called automatically when making a request if the client does not
310 already have a connection.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312
313.. method:: HTTPConnection.close()
314
315 Close the connection to the server.
316
317As an alternative to using the :meth:`request` method described above, you can
318also send your request step by step, by using the four functions below.
319
320
Georg Brandl036490d2009-05-17 13:00:36 +0000321.. method:: HTTPConnection.putrequest(request, selector, skip_host=False, skip_accept_encoding=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323 This should be the first call after the connection to the server has been made.
324 It sends a line to the server consisting of the *request* string, the *selector*
325 string, and the HTTP version (``HTTP/1.1``). To disable automatic sending of
326 ``Host:`` or ``Accept-Encoding:`` headers (for example to accept additional
327 content encodings), specify *skip_host* or *skip_accept_encoding* with non-False
328 values.
329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331.. method:: HTTPConnection.putheader(header, argument[, ...])
332
333 Send an :rfc:`822`\ -style header to the server. It sends a line to the server
334 consisting of the header, a colon and a space, and the first argument. If more
335 arguments are given, continuation lines are sent, each consisting of a tab and
336 an argument.
337
338
Senthil Kumaran5d0de3f2011-10-03 07:27:06 +0800339.. method:: HTTPConnection.endheaders(message_body=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Senthil Kumaran5d0de3f2011-10-03 07:27:06 +0800341 Send a blank line to the server, signalling the end of the headers. The
Senthil Kumaranad87fa62011-10-05 23:26:49 +0800342 optional *message_body* argument can be used to pass a message body
343 associated with the request. The message body will be sent in the same
344 packet as the message headers if it is string, otherwise it is sent in a
345 separate packet.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347.. method:: HTTPConnection.send(data)
348
349 Send data to the server. This should be used directly only after the
350 :meth:`endheaders` method has been called and before :meth:`getresponse` is
351 called.
352
353
354.. _httpresponse-objects:
355
356HTTPResponse Objects
357--------------------
358
Jeremy Hylton1052f892009-03-31 14:40:19 +0000359An :class:`HTTPResponse` instance wraps the HTTP response from the
360server. It provides access to the request headers and the entity
361body. The response is an iterable object and can be used in a with
362statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Martin Panterce911c32016-03-17 06:42:48 +0000364.. versionchanged:: 3.5
365 The :class:`io.BufferedIOBase` interface is now implemented and
366 all of its reader operations are supported.
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369.. method:: HTTPResponse.read([amt])
370
371 Reads and returns the response body, or up to the next *amt* bytes.
372
Antoine Pitrou38d96432011-12-06 22:33:57 +0100373.. method:: HTTPResponse.readinto(b)
374
375 Reads up to the next len(b) bytes of the response body into the buffer *b*.
376 Returns the number of bytes read.
377
378 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000379
Georg Brandl036490d2009-05-17 13:00:36 +0000380.. method:: HTTPResponse.getheader(name, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Senthil Kumaran790f8312010-08-02 17:09:02 +0000382 Return the value of the header *name*, or *default* if there is no header
383 matching *name*. If there is more than one header with the name *name*,
384 return all of the values joined by ', '. If 'default' is any iterable other
385 than a single string, its elements are similarly returned joined by commas.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387
388.. method:: HTTPResponse.getheaders()
389
390 Return a list of (header, value) tuples.
391
Senthil Kumaranceff5662010-09-21 01:57:43 +0000392.. method:: HTTPResponse.fileno()
393
394 Return the ``fileno`` of the underlying socket.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396.. attribute:: HTTPResponse.msg
397
Jeremy Hylton1052f892009-03-31 14:40:19 +0000398 A :class:`http.client.HTTPMessage` instance containing the response
399 headers. :class:`http.client.HTTPMessage` is a subclass of
400 :class:`email.message.Message`.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402
403.. attribute:: HTTPResponse.version
404
405 HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.
406
407
408.. attribute:: HTTPResponse.status
409
410 Status code returned by server.
411
412
413.. attribute:: HTTPResponse.reason
414
415 Reason phrase returned by server.
416
417
Jeremy Hylton1052f892009-03-31 14:40:19 +0000418.. attribute:: HTTPResponse.debuglevel
419
Georg Brandlef871f62010-03-12 10:06:40 +0000420 A debugging hook. If :attr:`debuglevel` is greater than zero, messages
Jeremy Hylton1052f892009-03-31 14:40:19 +0000421 will be printed to stdout as the response is read and parsed.
422
Senthil Kumarance9b5962011-06-19 16:56:49 -0700423.. attribute:: HTTPResponse.closed
424
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200425 Is ``True`` if the stream is closed.
Jeremy Hylton1052f892009-03-31 14:40:19 +0000426
Georg Brandl116aa622007-08-15 14:28:22 +0000427Examples
428--------
429
430Here is an example session that uses the ``GET`` method::
431
Georg Brandl24420152008-05-26 16:32:26 +0000432 >>> import http.client
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400433 >>> conn = http.client.HTTPSConnection("www.python.org")
434 >>> conn.request("GET", "/")
Georg Brandl116aa622007-08-15 14:28:22 +0000435 >>> r1 = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000436 >>> print(r1.status, r1.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000437 200 OK
Senthil Kumarance9b5962011-06-19 16:56:49 -0700438 >>> data1 = r1.read() # This will return entire content.
439 >>> # The following example demonstrates reading data in chunks.
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400440 >>> conn.request("GET", "/")
Senthil Kumarance9b5962011-06-19 16:56:49 -0700441 >>> r1 = conn.getresponse()
442 >>> while not r1.closed:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300443 ... print(r1.read(200)) # 200 bytes
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400444 b'<!doctype html>\n<!--[if"...
Senthil Kumarance9b5962011-06-19 16:56:49 -0700445 ...
446 >>> # Example of an invalid request
Georg Brandl116aa622007-08-15 14:28:22 +0000447 >>> conn.request("GET", "/parrot.spam")
448 >>> r2 = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000449 >>> print(r2.status, r2.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000450 404 Not Found
451 >>> data2 = r2.read()
452 >>> conn.close()
453
Fred Drake1587e3d2010-05-12 01:36:11 +0000454Here is an example session that uses the ``HEAD`` method. Note that the
455``HEAD`` method never returns any data. ::
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000456
457 >>> import http.client
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400458 >>> conn = http.client.HTTPSConnection("www.python.org")
459 >>> conn.request("HEAD", "/")
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000460 >>> res = conn.getresponse()
461 >>> print(res.status, res.reason)
462 200 OK
463 >>> data = res.read()
464 >>> print(len(data))
465 0
466 >>> data == b''
467 True
468
Georg Brandl116aa622007-08-15 14:28:22 +0000469Here is an example session that shows how to ``POST`` requests::
470
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000471 >>> import http.client, urllib.parse
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800472 >>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
Georg Brandl116aa622007-08-15 14:28:22 +0000473 >>> headers = {"Content-type": "application/x-www-form-urlencoded",
474 ... "Accept": "text/plain"}
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800475 >>> conn = http.client.HTTPConnection("bugs.python.org")
476 >>> conn.request("POST", "", params, headers)
Georg Brandl116aa622007-08-15 14:28:22 +0000477 >>> response = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000478 >>> print(response.status, response.reason)
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800479 302 Found
Georg Brandl116aa622007-08-15 14:28:22 +0000480 >>> data = response.read()
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800481 >>> data
482 b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
Georg Brandl116aa622007-08-15 14:28:22 +0000483 >>> conn.close()
484
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700485Client side ``HTTP PUT`` requests are very similar to ``POST`` requests. The
486difference lies only the server side where HTTP server will allow resources to
Senthil Kumarane66cc812013-03-13 13:42:47 -0700487be created via ``PUT`` request. It should be noted that custom HTTP methods
488+are also handled in :class:`urllib.request.Request` by sending the appropriate
489+method attribute.Here is an example session that shows how to do ``PUT``
490request using http.client::
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700491
492 >>> # This creates an HTTP message
493 >>> # with the content of BODY as the enclosed representation
Senthil Kumaran8b4a2722014-04-16 23:33:02 -0400494 >>> # for the resource http://localhost:8080/file
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700495 ...
496 >>> import http.client
497 >>> BODY = "***filecontents***"
498 >>> conn = http.client.HTTPConnection("localhost", 8080)
499 >>> conn.request("PUT", "/file", BODY)
500 >>> response = conn.getresponse()
Georg Brandld277a562013-10-06 12:42:18 +0200501 >>> print(response.status, response.reason)
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700502 200, OK
Jeremy Hylton1052f892009-03-31 14:40:19 +0000503
504.. _httpmessage-objects:
505
506HTTPMessage Objects
507-------------------
508
Benjamin Peterson605b9d92009-04-02 00:24:00 +0000509An :class:`http.client.HTTPMessage` instance holds the headers from an HTTP
510response. It is implemented using the :class:`email.message.Message` class.
Jeremy Hylton1052f892009-03-31 14:40:19 +0000511
Benjamin Peterson605b9d92009-04-02 00:24:00 +0000512.. XXX Define the methods that clients can depend upon between versions.