blob: 2f59ecebbd5bfe8b81e45eba28a875ff769ed985 [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
Andrew Kuchling58c534d2016-11-08 22:33:31 -050023 The `Requests package <http://docs.python-requests.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 Kumaran5dc504c2016-09-08 14:28:01 -070034.. class:: HTTPConnection(host, port=None[, timeout], source_address=None)
Georg Brandl116aa622007-08-15 14:28:22 +000035
36 An :class:`HTTPConnection` instance represents one transaction with an HTTP
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000037 server. It should be instantiated passing it a host and optional port
38 number. If no port number is passed, the port is extracted from the host
39 string if it has the form ``host:port``, else the default HTTP port (80) is
Antoine Pitrou988dbd72010-12-17 17:35:56 +000040 used. If the optional *timeout* parameter is given, blocking
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000041 operations (like connection attempts) will timeout after that many seconds
Georg Brandlf78e02b2008-06-10 17:40:04 +000042 (if it is not given, the global default timeout setting is used).
Raymond Hettinger519c3082011-01-30 00:39:00 +000043 The optional *source_address* parameter may be a tuple of a (host, port)
Gregory P. Smithb4066372010-01-03 03:28:29 +000044 to use as the source address the HTTP connection is made from.
Georg Brandl116aa622007-08-15 14:28:22 +000045
46 For example, the following calls all create instances that connect to the server
47 at the same host and port::
48
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010049 >>> h1 = http.client.HTTPConnection('www.python.org')
50 >>> h2 = http.client.HTTPConnection('www.python.org:80')
51 >>> h3 = http.client.HTTPConnection('www.python.org', 80)
52 >>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)
Georg Brandl116aa622007-08-15 14:28:22 +000053
Gregory P. Smithb4066372010-01-03 03:28:29 +000054 .. versionchanged:: 3.2
55 *source_address* was added.
Georg Brandl116aa622007-08-15 14:28:22 +000056
Senthil Kumaranaced69f2013-03-19 01:22:56 -070057 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -050058 The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
59 not longer supported.
Gregory P. Smithb4066372010-01-03 03:28:29 +000060
Antoine Pitrou988dbd72010-12-17 17:35:56 +000061
Ezio Melottie0add762012-09-14 06:32:35 +030062.. class:: HTTPSConnection(host, port=None, key_file=None, \
Senthil Kumaran052ddb02013-03-18 14:11:41 -070063 cert_file=None[, timeout], \
Ezio Melottie0add762012-09-14 06:32:35 +030064 source_address=None, *, context=None, \
65 check_hostname=None)
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 A subclass of :class:`HTTPConnection` that uses SSL for communication with
Antoine Pitrou803e6d62010-10-13 10:36:15 +000068 secure servers. Default port is ``443``. If *context* is specified, it
69 must be a :class:`ssl.SSLContext` instance describing the various SSL
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010070 options.
Georg Brandl116aa622007-08-15 14:28:22 +000071
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010072 Please read :ref:`ssl-security` for more information on best practices.
73
Gregory P. Smithb4066372010-01-03 03:28:29 +000074 .. versionchanged:: 3.2
Antoine Pitrou803e6d62010-10-13 10:36:15 +000075 *source_address*, *context* and *check_hostname* were added.
Gregory P. Smithb4066372010-01-03 03:28:29 +000076
Antoine Pitroud5323212010-10-22 18:19:07 +000077 .. versionchanged:: 3.2
78 This class now supports HTTPS virtual hosts if possible (that is,
79 if :data:`ssl.HAS_SNI` is true).
80
Senthil Kumaranaced69f2013-03-19 01:22:56 -070081 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -050082 The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
83 no longer supported.
Georg Brandl116aa622007-08-15 14:28:22 +000084
Benjamin Peterson4ffb0752014-11-03 14:29:33 -050085 .. versionchanged:: 3.4.3
86 This class now performs all the necessary certificate and hostname checks
87 by default. To revert to the previous, unverified, behavior
88 :func:`ssl._create_unverified_context` can be passed to the *context*
89 parameter.
90
Christian Heimesd0486372016-09-10 23:23:33 +020091 .. deprecated:: 3.6
92
93 *key_file* and *cert_file* are deprecated in favor of *context*.
94 Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
95 :func:`ssl.create_default_context` select the system's trusted CA
96 certificates for you.
97
98 The *check_hostname* parameter is also deprecated; the
99 :attr:`ssl.SSLContext.check_hostname` attribute of *context* should
100 be used instead.
101
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Senthil Kumaran052ddb02013-03-18 14:11:41 -0700103.. class:: HTTPResponse(sock, debuglevel=0, method=None, url=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Jeremy Hylton1052f892009-03-31 14:40:19 +0000105 Class whose instances are returned upon successful connection. Not
106 instantiated directly by user.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Senthil Kumaranaced69f2013-03-19 01:22:56 -0700108 .. versionchanged:: 3.4
R David Murray00569362014-01-03 13:04:25 -0500109 The *strict* parameter was removed. HTTP 0.9 style "Simple Responses" are
110 no longer supported.
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000111
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113The following exceptions are raised as appropriate:
114
115
116.. exception:: HTTPException
117
118 The base class of the other exceptions in this module. It is a subclass of
119 :exc:`Exception`.
120
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122.. exception:: NotConnected
123
124 A subclass of :exc:`HTTPException`.
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127.. exception:: InvalidURL
128
129 A subclass of :exc:`HTTPException`, raised if a port is given and is either
130 non-numeric or empty.
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133.. exception:: UnknownProtocol
134
135 A subclass of :exc:`HTTPException`.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. exception:: UnknownTransferEncoding
139
140 A subclass of :exc:`HTTPException`.
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143.. exception:: UnimplementedFileMode
144
145 A subclass of :exc:`HTTPException`.
146
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148.. exception:: IncompleteRead
149
150 A subclass of :exc:`HTTPException`.
151
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153.. exception:: ImproperConnectionState
154
155 A subclass of :exc:`HTTPException`.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. exception:: CannotSendRequest
159
160 A subclass of :exc:`ImproperConnectionState`.
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162
163.. exception:: CannotSendHeader
164
165 A subclass of :exc:`ImproperConnectionState`.
166
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168.. exception:: ResponseNotReady
169
170 A subclass of :exc:`ImproperConnectionState`.
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173.. exception:: BadStatusLine
174
175 A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP
176 status code that we don't understand.
177
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Berker Peksagbabc6882015-02-20 09:39:38 +0200179.. exception:: LineTooLong
180
181 A subclass of :exc:`HTTPException`. Raised if an excessively long line
182 is received in the HTTP protocol from the server.
183
184
R David Murraycae7bdb2015-04-05 19:26:29 -0400185.. exception:: RemoteDisconnected
186
187 A subclass of :exc:`ConnectionResetError` and :exc:`BadStatusLine`. Raised
188 by :meth:`HTTPConnection.getresponse` when the attempt to read the response
189 results in no data read from the connection, indicating that the remote end
190 has closed the connection.
191
192 .. versionadded:: 3.5
193 Previously, :exc:`BadStatusLine`\ ``('')`` was raised.
194
195
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100196The constants defined in this module are:
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198.. data:: HTTP_PORT
199
200 The default port for the HTTP protocol (always ``80``).
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202.. data:: HTTPS_PORT
203
204 The default port for the HTTPS protocol (always ``443``).
205
Georg Brandl116aa622007-08-15 14:28:22 +0000206.. data:: responses
207
208 This dictionary maps the HTTP 1.1 status codes to the W3C names.
209
Georg Brandl24420152008-05-26 16:32:26 +0000210 Example: ``http.client.responses[http.client.NOT_FOUND]`` is ``'Not Found'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Berker Peksagcb18b952015-01-20 06:30:46 +0200212See :ref:`http-status-codes` for a list of HTTP status codes that are
213available in this module as constants.
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216.. _httpconnection-objects:
217
218HTTPConnection Objects
219----------------------
220
221:class:`HTTPConnection` instances have the following methods:
222
223
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000224.. method:: HTTPConnection.request(method, url, body=None, headers={}, *, \
225 encode_chunked=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Jeremy Hylton236654b2009-03-27 20:24:34 +0000227 This will send a request to the server using the HTTP request
R David Murraybeed8402015-03-22 15:18:23 -0400228 method *method* and the selector *url*.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
R David Murraybeed8402015-03-22 15:18:23 -0400230 If *body* is specified, the specified data is sent after the headers are
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000231 finished. It may be a :class:`str`, a :term:`bytes-like object`, an
232 open :term:`file object`, or an iterable of :class:`bytes`. If *body*
233 is a string, it is encoded as ISO-8859-1, the default for HTTP. If it
234 is a bytes-like object, the bytes are sent as is. If it is a :term:`file
235 object`, the contents of the file is sent; this file object should
236 support at least the ``read()`` method. If the file object is an
237 instance of :class:`io.TextIOBase`, the data returned by the ``read()``
238 method will be encoded as ISO-8859-1, otherwise the data returned by
239 ``read()`` is sent as is. If *body* is an iterable, the elements of the
240 iterable are sent as is until the iterable is exhausted.
Jeremy Hylton236654b2009-03-27 20:24:34 +0000241
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000242 The *headers* argument should be a mapping of extra HTTP headers to send
243 with the request.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Martin Panteref91bb22016-08-27 01:39:26 +0000245 If *headers* contains neither Content-Length nor Transfer-Encoding,
246 but there is a request body, one of those
247 header fields will be added automatically. If
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000248 *body* is ``None``, the Content-Length header is set to ``0`` for
249 methods that expect a body (``PUT``, ``POST``, and ``PATCH``). If
Martin Panteref91bb22016-08-27 01:39:26 +0000250 *body* is a string or a bytes-like object that is not also a
251 :term:`file <file object>`, the Content-Length header is
252 set to its length. Any other type of *body* (files
253 and iterables in general) will be chunk-encoded, and the
254 Transfer-Encoding header will automatically be set instead of
255 Content-Length.
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000256
257 The *encode_chunked* argument is only relevant if Transfer-Encoding is
258 specified in *headers*. If *encode_chunked* is ``False``, the
259 HTTPConnection object assumes that all encoding is handled by the
260 calling code. If it is ``True``, the body will be chunk-encoded.
261
262 .. note::
263 Chunked transfer encoding has been added to the HTTP protocol
264 version 1.1. Unless the HTTP server is known to handle HTTP 1.1,
Martin Panteref91bb22016-08-27 01:39:26 +0000265 the caller must either specify the Content-Length, or must pass a
266 :class:`str` or bytes-like object that is not also a file as the
267 body representation.
R David Murraybeed8402015-03-22 15:18:23 -0400268
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000269 .. versionadded:: 3.2
Georg Brandl09a7df82010-12-19 12:33:52 +0000270 *body* can now be an iterable.
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000271
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000272 .. versionchanged:: 3.6
273 If neither Content-Length nor Transfer-Encoding are set in
Martin Panteref91bb22016-08-27 01:39:26 +0000274 *headers*, file and iterable *body* objects are now chunk-encoded.
275 The *encode_chunked* argument was added.
276 No attempt is made to determine the Content-Length for file
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000277 objects.
278
Georg Brandl116aa622007-08-15 14:28:22 +0000279.. method:: HTTPConnection.getresponse()
280
281 Should be called after a request is sent to get the response from the server.
282 Returns an :class:`HTTPResponse` instance.
283
284 .. note::
285
286 Note that you must have read the whole response before you can send a new
287 request to the server.
288
R David Murraycae7bdb2015-04-05 19:26:29 -0400289 .. versionchanged:: 3.5
290 If a :exc:`ConnectionError` or subclass is raised, the
291 :class:`HTTPConnection` object will be ready to reconnect when
292 a new request is sent.
293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295.. method:: HTTPConnection.set_debuglevel(level)
296
R. David Murrayd89bc3f2010-12-15 02:19:14 +0000297 Set the debugging level. The default debug level is ``0``, meaning no
298 debugging output is printed. Any value greater than ``0`` will cause all
299 currently defined debug output to be printed to stdout. The ``debuglevel``
300 is passed to any new :class:`HTTPResponse` objects that are created.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Mark Dickinson574b1d62009-10-01 20:20:09 +0000302 .. versionadded:: 3.1
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000303
Georg Brandl67b21b72010-08-17 15:07:14 +0000304
Senthil Kumaran7e5229c2009-12-20 07:31:21 +0000305.. method:: HTTPConnection.set_tunnel(host, port=None, headers=None)
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000306
Benjamin Petersona48d9ea2014-03-16 15:55:39 -0500307 Set the host and the port for HTTP Connect Tunnelling. This allows running
308 the connection through a proxy server.
Senthil Kumaran97f0c6b2009-07-25 04:24:38 +0000309
Benjamin Petersona48d9ea2014-03-16 15:55:39 -0500310 The host and port arguments specify the endpoint of the tunneled connection
311 (i.e. the address included in the CONNECT request, *not* the address of the
312 proxy server).
313
314 The headers argument should be a mapping of extra HTTP headers to send with
315 the CONNECT request.
316
317 For example, to tunnel through a HTTPS proxy server running locally on port
318 8080, we would pass the address of the proxy to the :class:`HTTPSConnection`
319 constructor, and the address of the host that we eventually want to reach to
320 the :meth:`~HTTPConnection.set_tunnel` method::
321
322 >>> import http.client
323 >>> conn = http.client.HTTPSConnection("localhost", 8080)
324 >>> conn.set_tunnel("www.python.org")
325 >>> conn.request("HEAD","/index.html")
Senthil Kumaran7e5229c2009-12-20 07:31:21 +0000326
Senthil Kumaran2e910fd2009-07-25 04:27:38 +0000327 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Georg Brandl67b21b72010-08-17 15:07:14 +0000329
Georg Brandl116aa622007-08-15 14:28:22 +0000330.. method:: HTTPConnection.connect()
331
R David Murraycae7bdb2015-04-05 19:26:29 -0400332 Connect to the server specified when the object was created. By default,
333 this is called automatically when making a request if the client does not
334 already have a connection.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336
337.. method:: HTTPConnection.close()
338
339 Close the connection to the server.
340
341As an alternative to using the :meth:`request` method described above, you can
342also send your request step by step, by using the four functions below.
343
344
Senthil Kumaran5dc504c2016-09-08 14:28:01 -0700345.. method:: HTTPConnection.putrequest(method, url, skip_host=False, \
346 skip_accept_encoding=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Senthil Kumaran5dc504c2016-09-08 14:28:01 -0700348 This should be the first call after the connection to the server has been
349 made. It sends a line to the server consisting of the *method* string,
350 the *url* string, and the HTTP version (``HTTP/1.1``). To disable automatic
351 sending of ``Host:`` or ``Accept-Encoding:`` headers (for example to accept
352 additional content encodings), specify *skip_host* or *skip_accept_encoding*
353 with non-False values.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356.. method:: HTTPConnection.putheader(header, argument[, ...])
357
358 Send an :rfc:`822`\ -style header to the server. It sends a line to the server
359 consisting of the header, a colon and a space, and the first argument. If more
360 arguments are given, continuation lines are sent, each consisting of a tab and
361 an argument.
362
363
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000364.. method:: HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Senthil Kumaran5d0de3f2011-10-03 07:27:06 +0800366 Send a blank line to the server, signalling the end of the headers. The
Senthil Kumaranad87fa62011-10-05 23:26:49 +0800367 optional *message_body* argument can be used to pass a message body
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000368 associated with the request.
369
370 If *encode_chunked* is ``True``, the result of each iteration of
371 *message_body* will be chunk-encoded as specified in :rfc:`7230`,
372 Section 3.3.1. How the data is encoded is dependent on the type of
373 *message_body*. If *message_body* implements the :ref:`buffer interface
374 <bufferobjects>` the encoding will result in a single chunk.
375 If *message_body* is a :class:`collections.Iterable`, each iteration
376 of *message_body* will result in a chunk. If *message_body* is a
377 :term:`file object`, each call to ``.read()`` will result in a chunk.
378 The method automatically signals the end of the chunk-encoded data
379 immediately after *message_body*.
380
381 .. note:: Due to the chunked encoding specification, empty chunks
382 yielded by an iterator body will be ignored by the chunk-encoder.
383 This is to avoid premature termination of the read of the request by
384 the target server due to malformed encoding.
385
386 .. versionadded:: 3.6
387 Chunked encoding support. The *encode_chunked* parameter was
388 added.
389
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391.. method:: HTTPConnection.send(data)
392
393 Send data to the server. This should be used directly only after the
394 :meth:`endheaders` method has been called and before :meth:`getresponse` is
395 called.
396
397
398.. _httpresponse-objects:
399
400HTTPResponse Objects
401--------------------
402
Jeremy Hylton1052f892009-03-31 14:40:19 +0000403An :class:`HTTPResponse` instance wraps the HTTP response from the
404server. It provides access to the request headers and the entity
405body. The response is an iterable object and can be used in a with
406statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Martin Panterce911c32016-03-17 06:42:48 +0000408.. versionchanged:: 3.5
409 The :class:`io.BufferedIOBase` interface is now implemented and
410 all of its reader operations are supported.
411
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413.. method:: HTTPResponse.read([amt])
414
415 Reads and returns the response body, or up to the next *amt* bytes.
416
Antoine Pitrou38d96432011-12-06 22:33:57 +0100417.. method:: HTTPResponse.readinto(b)
418
419 Reads up to the next len(b) bytes of the response body into the buffer *b*.
420 Returns the number of bytes read.
421
422 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000423
Georg Brandl036490d2009-05-17 13:00:36 +0000424.. method:: HTTPResponse.getheader(name, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Senthil Kumaran790f8312010-08-02 17:09:02 +0000426 Return the value of the header *name*, or *default* if there is no header
427 matching *name*. If there is more than one header with the name *name*,
428 return all of the values joined by ', '. If 'default' is any iterable other
429 than a single string, its elements are similarly returned joined by commas.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Georg Brandl116aa622007-08-15 14:28:22 +0000431.. method:: HTTPResponse.getheaders()
432
433 Return a list of (header, value) tuples.
434
Senthil Kumaranceff5662010-09-21 01:57:43 +0000435.. method:: HTTPResponse.fileno()
436
437 Return the ``fileno`` of the underlying socket.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439.. attribute:: HTTPResponse.msg
440
Jeremy Hylton1052f892009-03-31 14:40:19 +0000441 A :class:`http.client.HTTPMessage` instance containing the response
442 headers. :class:`http.client.HTTPMessage` is a subclass of
443 :class:`email.message.Message`.
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Georg Brandl116aa622007-08-15 14:28:22 +0000445.. attribute:: HTTPResponse.version
446
447 HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.
448
Georg Brandl116aa622007-08-15 14:28:22 +0000449.. attribute:: HTTPResponse.status
450
451 Status code returned by server.
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453.. attribute:: HTTPResponse.reason
454
455 Reason phrase returned by server.
456
Jeremy Hylton1052f892009-03-31 14:40:19 +0000457.. attribute:: HTTPResponse.debuglevel
458
Georg Brandlef871f62010-03-12 10:06:40 +0000459 A debugging hook. If :attr:`debuglevel` is greater than zero, messages
Jeremy Hylton1052f892009-03-31 14:40:19 +0000460 will be printed to stdout as the response is read and parsed.
461
Senthil Kumarance9b5962011-06-19 16:56:49 -0700462.. attribute:: HTTPResponse.closed
463
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200464 Is ``True`` if the stream is closed.
Jeremy Hylton1052f892009-03-31 14:40:19 +0000465
Georg Brandl116aa622007-08-15 14:28:22 +0000466Examples
467--------
468
469Here is an example session that uses the ``GET`` method::
470
Georg Brandl24420152008-05-26 16:32:26 +0000471 >>> import http.client
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400472 >>> conn = http.client.HTTPSConnection("www.python.org")
473 >>> conn.request("GET", "/")
Georg Brandl116aa622007-08-15 14:28:22 +0000474 >>> r1 = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000475 >>> print(r1.status, r1.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000476 200 OK
Senthil Kumarance9b5962011-06-19 16:56:49 -0700477 >>> data1 = r1.read() # This will return entire content.
478 >>> # The following example demonstrates reading data in chunks.
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400479 >>> conn.request("GET", "/")
Senthil Kumarance9b5962011-06-19 16:56:49 -0700480 >>> r1 = conn.getresponse()
481 >>> while not r1.closed:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300482 ... print(r1.read(200)) # 200 bytes
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400483 b'<!doctype html>\n<!--[if"...
Senthil Kumarance9b5962011-06-19 16:56:49 -0700484 ...
485 >>> # Example of an invalid request
Georg Brandl116aa622007-08-15 14:28:22 +0000486 >>> conn.request("GET", "/parrot.spam")
487 >>> r2 = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000488 >>> print(r2.status, r2.reason)
Georg Brandl116aa622007-08-15 14:28:22 +0000489 404 Not Found
490 >>> data2 = r2.read()
491 >>> conn.close()
492
Fred Drake1587e3d2010-05-12 01:36:11 +0000493Here is an example session that uses the ``HEAD`` method. Note that the
494``HEAD`` method never returns any data. ::
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000495
496 >>> import http.client
Benjamin Petersonac87ed72015-05-03 12:59:09 -0400497 >>> conn = http.client.HTTPSConnection("www.python.org")
498 >>> conn.request("HEAD", "/")
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000499 >>> res = conn.getresponse()
500 >>> print(res.status, res.reason)
501 200 OK
502 >>> data = res.read()
503 >>> print(len(data))
504 0
505 >>> data == b''
506 True
507
Georg Brandl116aa622007-08-15 14:28:22 +0000508Here is an example session that shows how to ``POST`` requests::
509
Senthil Kumaranaca8fd72008-06-23 04:41:59 +0000510 >>> import http.client, urllib.parse
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800511 >>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
Georg Brandl116aa622007-08-15 14:28:22 +0000512 >>> headers = {"Content-type": "application/x-www-form-urlencoded",
513 ... "Accept": "text/plain"}
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800514 >>> conn = http.client.HTTPConnection("bugs.python.org")
515 >>> conn.request("POST", "", params, headers)
Georg Brandl116aa622007-08-15 14:28:22 +0000516 >>> response = conn.getresponse()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000517 >>> print(response.status, response.reason)
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800518 302 Found
Georg Brandl116aa622007-08-15 14:28:22 +0000519 >>> data = response.read()
Senthil Kumaran96c84a42011-07-20 21:56:24 +0800520 >>> data
521 b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
Georg Brandl116aa622007-08-15 14:28:22 +0000522 >>> conn.close()
523
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700524Client side ``HTTP PUT`` requests are very similar to ``POST`` requests. The
525difference lies only the server side where HTTP server will allow resources to
Senthil Kumarane66cc812013-03-13 13:42:47 -0700526be created via ``PUT`` request. It should be noted that custom HTTP methods
527+are also handled in :class:`urllib.request.Request` by sending the appropriate
528+method attribute.Here is an example session that shows how to do ``PUT``
529request using http.client::
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700530
531 >>> # This creates an HTTP message
532 >>> # with the content of BODY as the enclosed representation
Senthil Kumaran8b4a2722014-04-16 23:33:02 -0400533 >>> # for the resource http://localhost:8080/file
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700534 ...
535 >>> import http.client
536 >>> BODY = "***filecontents***"
537 >>> conn = http.client.HTTPConnection("localhost", 8080)
538 >>> conn.request("PUT", "/file", BODY)
539 >>> response = conn.getresponse()
Georg Brandld277a562013-10-06 12:42:18 +0200540 >>> print(response.status, response.reason)
Senthil Kumaranb5fe2472013-03-13 13:38:33 -0700541 200, OK
Jeremy Hylton1052f892009-03-31 14:40:19 +0000542
543.. _httpmessage-objects:
544
545HTTPMessage Objects
546-------------------
547
Benjamin Peterson605b9d92009-04-02 00:24:00 +0000548An :class:`http.client.HTTPMessage` instance holds the headers from an HTTP
549response. It is implemented using the :class:`email.message.Message` class.
Jeremy Hylton1052f892009-03-31 14:40:19 +0000550
Benjamin Peterson605b9d92009-04-02 00:24:00 +0000551.. XXX Define the methods that clients can depend upon between versions.