blob: 56f4c0a0d772f49904512510b674e5a856061186 [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
Simon Legner112f2b82019-10-31 13:01:44 +010023 The `Requests package <https://requests.readthedocs.io/en/master/>`_
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
Nir Sofferad455cd2017-11-06 23:16:37 +020034.. class:: HTTPConnection(host, port=None[, timeout], source_address=None, \
35 blocksize=8192)
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.
Nir Sofferad455cd2017-11-06 23:16:37 +020046 The optional *blocksize* parameter sets the buffer size in bytes for
47 sending a file-like message body.
Georg Brandl116aa622007-08-15 14:28:22 +000048
49 For example, the following calls all create instances that connect to the server
50 at the same host and port::
51
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010052 >>> h1 = http.client.HTTPConnection('www.python.org')
53 >>> h2 = http.client.HTTPConnection('www.python.org:80')
54 >>> h3 = http.client.HTTPConnection('www.python.org', 80)
55 >>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)
Georg Brandl116aa622007-08-15 14:28:22 +000056
Gregory P. Smithb4066372010-01-03 03:28:29 +000057 .. versionchanged:: 3.2
58 *source_address* was added.
Georg Brandl116aa622007-08-15 14:28:22 +000059
Senthil Kumaranaced69f2013-03-19 01:22:56 -070060 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -050061 The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
62 not longer supported.
Gregory P. Smithb4066372010-01-03 03:28:29 +000063
Nir Sofferad455cd2017-11-06 23:16:37 +020064 .. versionchanged:: 3.7
65 *blocksize* parameter was added.
66
Antoine Pitrou988dbd72010-12-17 17:35:56 +000067
Ezio Melottie0add762012-09-14 06:32:35 +030068.. class:: HTTPSConnection(host, port=None, key_file=None, \
Senthil Kumaran052ddb02013-03-18 14:11:41 -070069 cert_file=None[, timeout], \
Ezio Melottie0add762012-09-14 06:32:35 +030070 source_address=None, *, context=None, \
Nir Sofferad455cd2017-11-06 23:16:37 +020071 check_hostname=None, blocksize=8192)
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 A subclass of :class:`HTTPConnection` that uses SSL for communication with
Antoine Pitrou803e6d62010-10-13 10:36:15 +000074 secure servers. Default port is ``443``. If *context* is specified, it
75 must be a :class:`ssl.SSLContext` instance describing the various SSL
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010076 options.
Georg Brandl116aa622007-08-15 14:28:22 +000077
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010078 Please read :ref:`ssl-security` for more information on best practices.
79
Gregory P. Smithb4066372010-01-03 03:28:29 +000080 .. versionchanged:: 3.2
Antoine Pitrou803e6d62010-10-13 10:36:15 +000081 *source_address*, *context* and *check_hostname* were added.
Gregory P. Smithb4066372010-01-03 03:28:29 +000082
Antoine Pitroud5323212010-10-22 18:19:07 +000083 .. versionchanged:: 3.2
84 This class now supports HTTPS virtual hosts if possible (that is,
85 if :data:`ssl.HAS_SNI` is true).
86
Senthil Kumaranaced69f2013-03-19 01:22:56 -070087 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -050088 The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
89 no longer supported.
Georg Brandl116aa622007-08-15 14:28:22 +000090
Benjamin Peterson4ffb0752014-11-03 14:29:33 -050091 .. versionchanged:: 3.4.3
92 This class now performs all the necessary certificate and hostname checks
93 by default. To revert to the previous, unverified, behavior
94 :func:`ssl._create_unverified_context` can be passed to the *context*
95 parameter.
96
Christian Heimesd1bd6e72019-07-01 08:32:24 +020097 .. versionchanged:: 3.8
98 This class now enables TLS 1.3
99 :attr:`ssl.SSLContext.post_handshake_auth` for the default *context* or
100 when *cert_file* is passed with a custom *context*.
101
Christian Heimesf97406b2020-11-13 16:37:52 +0100102 .. versionchanged:: 3.10
103 This class now sends an ALPN extension with protocol indicator
104 ``http/1.1`` when no *context* is given. Custom *context* should set
105 ALPN protocols with :meth:`~ssl.SSLContext.set_alpn_protocol`.
106
Christian Heimesd0486372016-09-10 23:23:33 +0200107 .. deprecated:: 3.6
108
109 *key_file* and *cert_file* are deprecated in favor of *context*.
110 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
111 :func:`ssl.create_default_context` select the system's trusted CA
112 certificates for you.
113
114 The *check_hostname* parameter is also deprecated; the
115 :attr:`ssl.SSLContext.check_hostname` attribute of *context* should
116 be used instead.
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Senthil Kumaran052ddb02013-03-18 14:11:41 -0700119.. class:: HTTPResponse(sock, debuglevel=0, method=None, url=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Jeremy Hylton1052f892009-03-31 14:40:19 +0000121 Class whose instances are returned upon successful connection. Not
122 instantiated directly by user.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
Senthil Kumaranaced69f2013-03-19 01:22:56 -0700124 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -0500125 The *strict* parameter was removed. HTTP 0.9 style "Simple Responses" are
126 no longer supported.
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000127
Ashwin Ramaswami478f8292019-01-18 07:49:16 -0800128This module provides the following function:
129
130.. function:: parse_headers(fp)
131
132 Parse the headers from a file pointer *fp* representing a HTTP
133 request/response. The file has to be a :class:`BufferedIOBase` reader
134 (i.e. not text) and must provide a valid :rfc:`2822` style header.
135
136 This function returns an instance of :class:`http.client.HTTPMessage`
137 that holds the header fields, but no payload
138 (the same as :attr:`HTTPResponse.msg`
139 and :attr:`http.server.BaseHTTPRequestHandler.headers`).
140 After returning, the file pointer *fp* is ready to read the HTTP body.
141
142 .. note::
143 :meth:`parse_headers` does not parse the start-line of a HTTP message;
144 it only parses the ``Name: value`` lines. The file has to be ready to
145 read these field lines, so the first line should already be consumed
146 before calling the function.
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148The following exceptions are raised as appropriate:
149
150
151.. exception:: HTTPException
152
153 The base class of the other exceptions in this module. It is a subclass of
154 :exc:`Exception`.
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157.. exception:: NotConnected
158
159 A subclass of :exc:`HTTPException`.
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162.. exception:: InvalidURL
163
164 A subclass of :exc:`HTTPException`, raised if a port is given and is either
165 non-numeric or empty.
166
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168.. exception:: UnknownProtocol
169
170 A subclass of :exc:`HTTPException`.
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173.. exception:: UnknownTransferEncoding
174
175 A subclass of :exc:`HTTPException`.
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. exception:: UnimplementedFileMode
179
180 A subclass of :exc:`HTTPException`.
181
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183.. exception:: IncompleteRead
184
185 A subclass of :exc:`HTTPException`.
186
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188.. exception:: ImproperConnectionState
189
190 A subclass of :exc:`HTTPException`.
191
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193.. exception:: CannotSendRequest
194
195 A subclass of :exc:`ImproperConnectionState`.
196
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198.. exception:: CannotSendHeader
199
200 A subclass of :exc:`ImproperConnectionState`.
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203.. exception:: ResponseNotReady
204
205 A subclass of :exc:`ImproperConnectionState`.
206
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208.. exception:: BadStatusLine
209
210 A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP
211 status code that we don't understand.
212
Georg Brandl116aa622007-08-15 14:28:22 +0000213
Berker Peksagbabc6882015-02-20 09:39:38 +0200214.. exception:: LineTooLong
215
216 A subclass of :exc:`HTTPException`. Raised if an excessively long line
217 is received in the HTTP protocol from the server.
218
219
R David Murraycae7bdb2015-04-05 19:26:29 -0400220.. exception:: RemoteDisconnected
221
222 A subclass of :exc:`ConnectionResetError` and :exc:`BadStatusLine`. Raised
223 by :meth:`HTTPConnection.getresponse` when the attempt to read the response
224 results in no data read from the connection, indicating that the remote end
225 has closed the connection.
226
227 .. versionadded:: 3.5
228 Previously, :exc:`BadStatusLine`\ ``('')`` was raised.
229
230
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100231The constants defined in this module are:
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233.. data:: HTTP_PORT
234
235 The default port for the HTTP protocol (always ``80``).
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237.. data:: HTTPS_PORT
238
239 The default port for the HTTPS protocol (always ``443``).
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241.. data:: responses
242
243 This dictionary maps the HTTP 1.1 status codes to the W3C names.
244
Georg Brandl24420152008-05-26 16:32:26 +0000245 Example: ``http.client.responses[http.client.NOT_FOUND]`` is ``'Not Found'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Berker Peksagcb18b952015-01-20 06:30:46 +0200247See :ref:`http-status-codes` for a list of HTTP status codes that are
248available in this module as constants.
249
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251.. _httpconnection-objects:
252
253HTTPConnection Objects
254----------------------
255
256:class:`HTTPConnection` instances have the following methods:
257
258
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000259.. method:: HTTPConnection.request(method, url, body=None, headers={}, *, \
260 encode_chunked=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Jeremy Hylton236654b2009-03-27 20:24:34 +0000262 This will send a request to the server using the HTTP request
R David Murraybeed8402015-03-22 15:18:23 -0400263 method *method* and the selector *url*.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
R David Murraybeed8402015-03-22 15:18:23 -0400265 If *body* is specified, the specified data is sent after the headers are
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000266 finished. It may be a :class:`str`, a :term:`bytes-like object`, an
267 open :term:`file object`, or an iterable of :class:`bytes`. If *body*
268 is a string, it is encoded as ISO-8859-1, the default for HTTP. If it
269 is a bytes-like object, the bytes are sent as is. If it is a :term:`file
270 object`, the contents of the file is sent; this file object should
271 support at least the ``read()`` method. If the file object is an
272 instance of :class:`io.TextIOBase`, the data returned by the ``read()``
273 method will be encoded as ISO-8859-1, otherwise the data returned by
274 ``read()`` is sent as is. If *body* is an iterable, the elements of the
275 iterable are sent as is until the iterable is exhausted.
Jeremy Hylton236654b2009-03-27 20:24:34 +0000276
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000277 The *headers* argument should be a mapping of extra HTTP headers to send
278 with the request.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Martin Panteref91bb22016-08-27 01:39:26 +0000280 If *headers* contains neither Content-Length nor Transfer-Encoding,
281 but there is a request body, one of those
282 header fields will be added automatically. If
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000283 *body* is ``None``, the Content-Length header is set to ``0`` for
284 methods that expect a body (``PUT``, ``POST``, and ``PATCH``). If
Martin Panteref91bb22016-08-27 01:39:26 +0000285 *body* is a string or a bytes-like object that is not also a
286 :term:`file <file object>`, the Content-Length header is
287 set to its length. Any other type of *body* (files
288 and iterables in general) will be chunk-encoded, and the
289 Transfer-Encoding header will automatically be set instead of
290 Content-Length.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000291
292 The *encode_chunked* argument is only relevant if Transfer-Encoding is
293 specified in *headers*. If *encode_chunked* is ``False``, the
294 HTTPConnection object assumes that all encoding is handled by the
295 calling code. If it is ``True``, the body will be chunk-encoded.
296
297 .. note::
298 Chunked transfer encoding has been added to the HTTP protocol
299 version 1.1. Unless the HTTP server is known to handle HTTP 1.1,
Martin Panteref91bb22016-08-27 01:39:26 +0000300 the caller must either specify the Content-Length, or must pass a
301 :class:`str` or bytes-like object that is not also a file as the
302 body representation.
R David Murraybeed8402015-03-22 15:18:23 -0400303
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000304 .. versionadded:: 3.2
Georg Brandl09a7df82010-12-19 12:33:52 +0000305 *body* can now be an iterable.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000306
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000307 .. versionchanged:: 3.6
308 If neither Content-Length nor Transfer-Encoding are set in
Martin Panteref91bb22016-08-27 01:39:26 +0000309 *headers*, file and iterable *body* objects are now chunk-encoded.
310 The *encode_chunked* argument was added.
311 No attempt is made to determine the Content-Length for file
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000312 objects.
313
Georg Brandl116aa622007-08-15 14:28:22 +0000314.. method:: HTTPConnection.getresponse()
315
316 Should be called after a request is sent to get the response from the server.
317 Returns an :class:`HTTPResponse` instance.
318
319 .. note::
320
321 Note that you must have read the whole response before you can send a new
322 request to the server.
323
R David Murraycae7bdb2015-04-05 19:26:29 -0400324 .. versionchanged:: 3.5
325 If a :exc:`ConnectionError` or subclass is raised, the
326 :class:`HTTPConnection` object will be ready to reconnect when
327 a new request is sent.
328
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. method:: HTTPConnection.set_debuglevel(level)
331
R. David Murrayd89bc3f2010-12-15 02:19:14 +0000332 Set the debugging level. The default debug level is ``0``, meaning no
333 debugging output is printed. Any value greater than ``0`` will cause all
334 currently defined debug output to be printed to stdout. The ``debuglevel``
335 is passed to any new :class:`HTTPResponse` objects that are created.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Mark Dickinson574b1d62009-10-01 20:20:09 +0000337 .. versionadded:: 3.1
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000338
Georg Brandl67b21b72010-08-17 15:07:14 +0000339
Senthil Kumaran7e5229c2009-12-20 07:31:21 +0000340.. method:: HTTPConnection.set_tunnel(host, port=None, headers=None)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000341
Benjamin Petersona48d9ea2014-03-16 15:55:39 -0500342 Set the host and the port for HTTP Connect Tunnelling. This allows running
343 the connection through a proxy server.
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000344
Benjamin Petersona48d9ea2014-03-16 15:55:39 -0500345 The host and port arguments specify the endpoint of the tunneled connection
346 (i.e. the address included in the CONNECT request, *not* the address of the
347 proxy server).
348
349 The headers argument should be a mapping of extra HTTP headers to send with
350 the CONNECT request.
351
352 For example, to tunnel through a HTTPS proxy server running locally on port
353 8080, we would pass the address of the proxy to the :class:`HTTPSConnection`
354 constructor, and the address of the host that we eventually want to reach to
355 the :meth:`~HTTPConnection.set_tunnel` method::
356
357 >>> import http.client
358 >>> conn = http.client.HTTPSConnection("localhost", 8080)
359 >>> conn.set_tunnel("www.python.org")
360 >>> conn.request("HEAD","/index.html")
Senthil Kumaran7e5229c2009-12-20 07:31:21 +0000361
Senthil Kumaran2e910fd2009-07-25 04:27:38 +0000362 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Georg Brandl67b21b72010-08-17 15:07:14 +0000364
Georg Brandl116aa622007-08-15 14:28:22 +0000365.. method:: HTTPConnection.connect()
366
R David Murraycae7bdb2015-04-05 19:26:29 -0400367 Connect to the server specified when the object was created. By default,
368 this is called automatically when making a request if the client does not
369 already have a connection.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371
372.. method:: HTTPConnection.close()
373
374 Close the connection to the server.
375
Nir Sofferad455cd2017-11-06 23:16:37 +0200376
377.. attribute:: HTTPConnection.blocksize
378
379 Buffer size in bytes for sending a file-like message body.
380
381 .. versionadded:: 3.7
382
383
Georg Brandl116aa622007-08-15 14:28:22 +0000384As an alternative to using the :meth:`request` method described above, you can
385also send your request step by step, by using the four functions below.
386
387
Senthil Kumaran5dc504c2016-09-08 14:28:01 -0700388.. method:: HTTPConnection.putrequest(method, url, skip_host=False, \
389 skip_accept_encoding=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Senthil Kumaran5dc504c2016-09-08 14:28:01 -0700391 This should be the first call after the connection to the server has been
392 made. It sends a line to the server consisting of the *method* string,
393 the *url* string, and the HTTP version (``HTTP/1.1``). To disable automatic
394 sending of ``Host:`` or ``Accept-Encoding:`` headers (for example to accept
395 additional content encodings), specify *skip_host* or *skip_accept_encoding*
396 with non-False values.
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399.. method:: HTTPConnection.putheader(header, argument[, ...])
400
401 Send an :rfc:`822`\ -style header to the server. It sends a line to the server
402 consisting of the header, a colon and a space, and the first argument. If more
403 arguments are given, continuation lines are sent, each consisting of a tab and
404 an argument.
405
406
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000407.. method:: HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Senthil Kumaran5d0de3f2011-10-03 07:27:06 +0800409 Send a blank line to the server, signalling the end of the headers. The
Senthil Kumaranad87fa62011-10-05 23:26:49 +0800410 optional *message_body* argument can be used to pass a message body
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000411 associated with the request.
412
413 If *encode_chunked* is ``True``, the result of each iteration of
414 *message_body* will be chunk-encoded as specified in :rfc:`7230`,
415 Section 3.3.1. How the data is encoded is dependent on the type of
416 *message_body*. If *message_body* implements the :ref:`buffer interface
417 <bufferobjects>` the encoding will result in a single chunk.
Serhiy Storchaka2e576f52017-04-24 09:05:00 +0300418 If *message_body* is a :class:`collections.abc.Iterable`, each iteration
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000419 of *message_body* will result in a chunk. If *message_body* is a
420 :term:`file object`, each call to ``.read()`` will result in a chunk.
421 The method automatically signals the end of the chunk-encoded data
422 immediately after *message_body*.
423
424 .. note:: Due to the chunked encoding specification, empty chunks
425 yielded by an iterator body will be ignored by the chunk-encoder.
426 This is to avoid premature termination of the read of the request by
427 the target server due to malformed encoding.
428
429 .. versionadded:: 3.6
430 Chunked encoding support. The *encode_chunked* parameter was
431 added.
432
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434.. method:: HTTPConnection.send(data)
435
436 Send data to the server. This should be used directly only after the
437 :meth:`endheaders` method has been called and before :meth:`getresponse` is
438 called.
439
440
441.. _httpresponse-objects:
442
443HTTPResponse Objects
444--------------------
445
Jeremy Hylton1052f892009-03-31 14:40:19 +0000446An :class:`HTTPResponse` instance wraps the HTTP response from the
447server. It provides access to the request headers and the entity
448body. The response is an iterable object and can be used in a with
449statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000450
Martin Panterce911c32016-03-17 06:42:48 +0000451.. versionchanged:: 3.5
452 The :class:`io.BufferedIOBase` interface is now implemented and
453 all of its reader operations are supported.
454
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456.. method:: HTTPResponse.read([amt])
457
458 Reads and returns the response body, or up to the next *amt* bytes.
459
Antoine Pitrou38d96432011-12-06 22:33:57 +0100460.. method:: HTTPResponse.readinto(b)
461
462 Reads up to the next len(b) bytes of the response body into the buffer *b*.
463 Returns the number of bytes read.
464
465 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000466
Georg Brandl036490d2009-05-17 13:00:36 +0000467.. method:: HTTPResponse.getheader(name, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Senthil Kumaran790f8312010-08-02 17:09:02 +0000469 Return the value of the header *name*, or *default* if there is no header
470 matching *name*. If there is more than one header with the name *name*,
471 return all of the values joined by ', '. If 'default' is any iterable other
472 than a single string, its elements are similarly returned joined by commas.
Georg Brandl116aa622007-08-15 14:28:22 +0000473
Georg Brandl116aa622007-08-15 14:28:22 +0000474.. method:: HTTPResponse.getheaders()
475
476 Return a list of (header, value) tuples.
477
Senthil Kumaranceff5662010-09-21 01:57:43 +0000478.. method:: HTTPResponse.fileno()
479
480 Return the ``fileno`` of the underlying socket.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482.. attribute:: HTTPResponse.msg
483
Jeremy Hylton1052f892009-03-31 14:40:19 +0000484 A :class:`http.client.HTTPMessage` instance containing the response
485 headers. :class:`http.client.HTTPMessage` is a subclass of
486 :class:`email.message.Message`.
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Georg Brandl116aa622007-08-15 14:28:22 +0000488.. attribute:: HTTPResponse.version
489
490 HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.
491
Ashwin Ramaswamiff2e1822019-09-13 04:40:08 -0700492.. attribute:: HTTPResponse.url
493
494 URL of the resource retrieved, commonly used to determine if a redirect was followed.
495
496.. attribute:: HTTPResponse.headers
497
498 Headers of the response in the form of an :class:`email.message.EmailMessage` instance.
499
Georg Brandl116aa622007-08-15 14:28:22 +0000500.. attribute:: HTTPResponse.status
501
502 Status code returned by server.
503
Georg Brandl116aa622007-08-15 14:28:22 +0000504.. attribute:: HTTPResponse.reason
505
506 Reason phrase returned by server.
507
Jeremy Hylton1052f892009-03-31 14:40:19 +0000508.. attribute:: HTTPResponse.debuglevel
509
Georg Brandlef871f62010-03-12 10:06:40 +0000510 A debugging hook. If :attr:`debuglevel` is greater than zero, messages
Jeremy Hylton1052f892009-03-31 14:40:19 +0000511 will be printed to stdout as the response is read and parsed.
512
Senthil Kumarance9b5962011-06-19 16:56:49 -0700513.. attribute:: HTTPResponse.closed
514
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200515 Is ``True`` if the stream is closed.
Jeremy Hylton1052f892009-03-31 14:40:19 +0000516
Ashwin Ramaswamiff2e1822019-09-13 04:40:08 -0700517.. method:: HTTPResponse.geturl()
518
519 .. deprecated:: 3.9
520 Deprecated in favor of :attr:`~HTTPResponse.url`.
521
522.. method:: HTTPResponse.info()
523
524 .. deprecated:: 3.9
525 Deprecated in favor of :attr:`~HTTPResponse.headers`.
526
527.. method:: HTTPResponse.getstatus()
528
529 .. deprecated:: 3.9
530 Deprecated in favor of :attr:`~HTTPResponse.status`.
531
Georg Brandl116aa622007-08-15 14:28:22 +0000532Examples
533--------
534
535Here is an example session that uses the ``GET`` method::
536
Georg Brandl24420152008-05-26 16:32:26 +0000537 >>> import http.client
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400538 >>> conn = http.client.HTTPSConnection("www.python.org")
539 >>> conn.request("GET", "/")
Georg Brandl116aa622007-08-15 14:28:22 +0000540 >>> r1 = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000541 >>> print(r1.status, r1.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000542 200 OK
Senthil Kumarance9b5962011-06-19 16:56:49 -0700543 >>> data1 = r1.read() # This will return entire content.
544 >>> # The following example demonstrates reading data in chunks.
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400545 >>> conn.request("GET", "/")
Senthil Kumarance9b5962011-06-19 16:56:49 -0700546 >>> r1 = conn.getresponse()
Julien Palarde1d455f2019-09-11 15:01:18 +0200547 >>> while chunk := r1.read(200):
Ashwin Ramaswami62cf6982019-09-11 05:41:54 -0700548 ... print(repr(chunk))
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400549 b'<!doctype html>\n<!--[if"...
Senthil Kumarance9b5962011-06-19 16:56:49 -0700550 ...
551 >>> # Example of an invalid request
Xtreakf0af4c52018-12-21 21:04:41 +0530552 >>> conn = http.client.HTTPSConnection("docs.python.org")
Georg Brandl116aa622007-08-15 14:28:22 +0000553 >>> conn.request("GET", "/parrot.spam")
554 >>> r2 = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000555 >>> print(r2.status, r2.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000556 404 Not Found
557 >>> data2 = r2.read()
558 >>> conn.close()
559
Fred Drake1587e3d2010-05-12 01:36:11 +0000560Here is an example session that uses the ``HEAD`` method. Note that the
561``HEAD`` method never returns any data. ::
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000562
563 >>> import http.client
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400564 >>> conn = http.client.HTTPSConnection("www.python.org")
565 >>> conn.request("HEAD", "/")
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000566 >>> res = conn.getresponse()
567 >>> print(res.status, res.reason)
568 200 OK
569 >>> data = res.read()
570 >>> print(len(data))
571 0
572 >>> data == b''
573 True
574
Georg Brandl116aa622007-08-15 14:28:22 +0000575Here is an example session that shows how to ``POST`` requests::
576
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000577 >>> import http.client, urllib.parse
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800578 >>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
Georg Brandl116aa622007-08-15 14:28:22 +0000579 >>> headers = {"Content-type": "application/x-www-form-urlencoded",
580 ... "Accept": "text/plain"}
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800581 >>> conn = http.client.HTTPConnection("bugs.python.org")
582 >>> conn.request("POST", "", params, headers)
Georg Brandl116aa622007-08-15 14:28:22 +0000583 >>> response = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000584 >>> print(response.status, response.reason)
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800585 302 Found
Georg Brandl116aa622007-08-15 14:28:22 +0000586 >>> data = response.read()
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800587 >>> data
588 b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
Georg Brandl116aa622007-08-15 14:28:22 +0000589 >>> conn.close()
590
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700591Client side ``HTTP PUT`` requests are very similar to ``POST`` requests. The
592difference lies only the server side where HTTP server will allow resources to
Senthil Kumarane66cc812013-03-13 13:42:47 -0700593be created via ``PUT`` request. It should be noted that custom HTTP methods
James Corbettb94737a2020-02-01 04:31:00 -0800594are also handled in :class:`urllib.request.Request` by setting the appropriate
595method attribute. Here is an example session that shows how to send a ``PUT``
Senthil Kumarane66cc812013-03-13 13:42:47 -0700596request using http.client::
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700597
598 >>> # This creates an HTTP message
599 >>> # with the content of BODY as the enclosed representation
Senthil Kumaran8b4a2722014-04-16 23:33:02 -0400600 >>> # for the resource http://localhost:8080/file
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700601 ...
602 >>> import http.client
603 >>> BODY = "***filecontents***"
604 >>> conn = http.client.HTTPConnection("localhost", 8080)
605 >>> conn.request("PUT", "/file", BODY)
606 >>> response = conn.getresponse()
Georg Brandld277a562013-10-06 12:42:18 +0200607 >>> print(response.status, response.reason)
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700608 200, OK
Jeremy Hylton1052f892009-03-31 14:40:19 +0000609
610.. _httpmessage-objects:
611
612HTTPMessage Objects
613-------------------
614
Benjamin Peterson605b9d92009-04-02 00:24:00 +0000615An :class:`http.client.HTTPMessage` instance holds the headers from an HTTP
616response. It is implemented using the :class:`email.message.Message` class.
Jeremy Hylton1052f892009-03-31 14:40:19 +0000617
Benjamin Peterson605b9d92009-04-02 00:24:00 +0000618.. XXX Define the methods that clients can depend upon between versions.