• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`httplib` --- HTTP protocol client
2=======================================
3
4.. module:: httplib
5   :synopsis: HTTP and HTTPS protocol client (requires sockets).
6
7.. note::
8   The :mod:`httplib` module has been renamed to :mod:`http.client` in Python
9   3.  The :term:`2to3` tool will automatically adapt imports when converting
10   your sources to Python 3.
11
12
13.. index::
14   pair: HTTP; protocol
15   single: HTTP; httplib (standard module)
16
17.. index:: module: urllib
18
19**Source code:** :source:`Lib/httplib.py`
20
21--------------
22
23This module defines classes which implement the client side of the HTTP and
24HTTPS protocols.  It is normally not used directly --- the module :mod:`urllib`
25uses it to handle URLs that use HTTP and HTTPS.
26
27.. seealso::
28
29    The `Requests package <http://requests.readthedocs.org/>`_
30    is recommended for a higher-level HTTP client interface.
31
32.. note::
33
34   HTTPS support is only available if the :mod:`socket` module was compiled with
35   SSL support.
36
37.. note::
38
39   The public interface for this module changed substantially in Python 2.0.  The
40   :class:`HTTP` class is retained only for backward compatibility with 1.5.2.  It
41   should not be used in new code.  Refer to the online docstrings for usage.
42
43The module provides the following classes:
44
45
46.. class:: HTTPConnection(host[, port[, strict[, timeout[, source_address]]]])
47
48   An :class:`HTTPConnection` instance represents one transaction with an HTTP
49   server.  It should be instantiated passing it a host and optional port
50   number.  If no port number is passed, the port is extracted from the host
51   string if it has the form ``host:port``, else the default HTTP port (80) is
52   used.  When true, the optional parameter *strict* (which defaults to a false
53   value) causes ``BadStatusLine`` to
54   be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1
55   status line.  If the optional *timeout* parameter is given, blocking
56   operations (like connection attempts) will timeout after that many seconds
57   (if it is not given, the global default timeout setting is used).
58   The optional *source_address* parameter may be a tuple of a (host, port)
59   to use as the source address the HTTP connection is made from.
60
61   For example, the following calls all create instances that connect to the server
62   at the same host and port::
63
64      >>> h1 = httplib.HTTPConnection('www.cwi.nl')
65      >>> h2 = httplib.HTTPConnection('www.cwi.nl:80')
66      >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80)
67      >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10)
68
69   .. versionadded:: 2.0
70
71   .. versionchanged:: 2.6
72      *timeout* was added.
73
74   .. versionchanged:: 2.7
75      *source_address* was added.
76
77
78.. class:: HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout[, source_address[, context]]]]]]])
79
80   A subclass of :class:`HTTPConnection` that uses SSL for communication with
81   secure servers.  Default port is ``443``.  If *context* is specified, it must
82   be a :class:`ssl.SSLContext` instance describing the various SSL options.
83
84   *key_file* and *cert_file* are deprecated, please use
85   :meth:`ssl.SSLContext.load_cert_chain` instead, or let
86   :func:`ssl.create_default_context` select the system's trusted CA
87   certificates for you.
88
89   Please read :ref:`ssl-security` for more information on best practices.
90
91   .. versionadded:: 2.0
92
93   .. versionchanged:: 2.6
94      *timeout* was added.
95
96   .. versionchanged:: 2.7
97      *source_address* was added.
98
99   .. versionchanged:: 2.7.9
100      *context* was added.
101
102      This class now performs all the necessary certificate and hostname checks
103      by default. To revert to the previous, unverified, behavior
104      :func:`ssl._create_unverified_context` can be passed to the *context*
105      parameter.
106
107
108.. class:: HTTPResponse(sock, debuglevel=0, strict=0)
109
110   Class whose instances are returned upon successful connection.  Not instantiated
111   directly by user.
112
113   .. versionadded:: 2.0
114
115.. class:: HTTPMessage
116
117   An :class:`HTTPMessage` instance is used to hold the headers from an HTTP
118   response. It is implemented using the :class:`mimetools.Message` class and
119   provides utility functions to deal with HTTP Headers. It is not directly
120   instantiated by the users.
121
122
123The following exceptions are raised as appropriate:
124
125
126.. exception:: HTTPException
127
128   The base class of the other exceptions in this module.  It is a subclass of
129   :exc:`Exception`.
130
131   .. versionadded:: 2.0
132
133
134.. exception:: NotConnected
135
136   A subclass of :exc:`HTTPException`.
137
138   .. versionadded:: 2.0
139
140
141.. exception:: InvalidURL
142
143   A subclass of :exc:`HTTPException`, raised if a port is given and is either
144   non-numeric or empty.
145
146   .. versionadded:: 2.3
147
148
149.. exception:: UnknownProtocol
150
151   A subclass of :exc:`HTTPException`.
152
153   .. versionadded:: 2.0
154
155
156.. exception:: UnknownTransferEncoding
157
158   A subclass of :exc:`HTTPException`.
159
160   .. versionadded:: 2.0
161
162
163.. exception:: UnimplementedFileMode
164
165   A subclass of :exc:`HTTPException`.
166
167   .. versionadded:: 2.0
168
169
170.. exception:: IncompleteRead
171
172   A subclass of :exc:`HTTPException`.
173
174   .. versionadded:: 2.0
175
176
177.. exception:: ImproperConnectionState
178
179   A subclass of :exc:`HTTPException`.
180
181   .. versionadded:: 2.0
182
183
184.. exception:: CannotSendRequest
185
186   A subclass of :exc:`ImproperConnectionState`.
187
188   .. versionadded:: 2.0
189
190
191.. exception:: CannotSendHeader
192
193   A subclass of :exc:`ImproperConnectionState`.
194
195   .. versionadded:: 2.0
196
197
198.. exception:: ResponseNotReady
199
200   A subclass of :exc:`ImproperConnectionState`.
201
202   .. versionadded:: 2.0
203
204
205.. exception:: BadStatusLine
206
207   A subclass of :exc:`HTTPException`.  Raised if a server responds with a HTTP
208   status code that we don't understand.
209
210   .. versionadded:: 2.0
211
212The constants defined in this module are:
213
214
215.. data:: HTTP_PORT
216
217   The default port for the HTTP protocol (always ``80``).
218
219
220.. data:: HTTPS_PORT
221
222   The default port for the HTTPS protocol (always ``443``).
223
224and also the following constants for integer status codes:
225
226+------------------------------------------+---------+-----------------------------------------------------------------------+
227| Constant                                 | Value   | Definition                                                            |
228+==========================================+=========+=======================================================================+
229| :const:`CONTINUE`                        | ``100`` | HTTP/1.1, `RFC 2616, Section                                          |
230|                                          |         | 10.1.1                                                                |
231|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1>`_  |
232+------------------------------------------+---------+-----------------------------------------------------------------------+
233| :const:`SWITCHING_PROTOCOLS`             | ``101`` | HTTP/1.1, `RFC 2616, Section                                          |
234|                                          |         | 10.1.2                                                                |
235|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.2>`_  |
236+------------------------------------------+---------+-----------------------------------------------------------------------+
237| :const:`PROCESSING`                      | ``102`` | WEBDAV, `RFC 2518, Section 10.1                                       |
238|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_102>`_               |
239+------------------------------------------+---------+-----------------------------------------------------------------------+
240| :const:`OK`                              | ``200`` | HTTP/1.1, `RFC 2616, Section                                          |
241|                                          |         | 10.2.1                                                                |
242|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1>`_  |
243+------------------------------------------+---------+-----------------------------------------------------------------------+
244| :const:`CREATED`                         | ``201`` | HTTP/1.1, `RFC 2616, Section                                          |
245|                                          |         | 10.2.2                                                                |
246|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2>`_  |
247+------------------------------------------+---------+-----------------------------------------------------------------------+
248| :const:`ACCEPTED`                        | ``202`` | HTTP/1.1, `RFC 2616, Section                                          |
249|                                          |         | 10.2.3                                                                |
250|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3>`_  |
251+------------------------------------------+---------+-----------------------------------------------------------------------+
252| :const:`NON_AUTHORITATIVE_INFORMATION`   | ``203`` | HTTP/1.1, `RFC 2616, Section                                          |
253|                                          |         | 10.2.4                                                                |
254|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.4>`_  |
255+------------------------------------------+---------+-----------------------------------------------------------------------+
256| :const:`NO_CONTENT`                      | ``204`` | HTTP/1.1, `RFC 2616, Section                                          |
257|                                          |         | 10.2.5                                                                |
258|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5>`_  |
259+------------------------------------------+---------+-----------------------------------------------------------------------+
260| :const:`RESET_CONTENT`                   | ``205`` | HTTP/1.1, `RFC 2616, Section                                          |
261|                                          |         | 10.2.6                                                                |
262|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.6>`_  |
263+------------------------------------------+---------+-----------------------------------------------------------------------+
264| :const:`PARTIAL_CONTENT`                 | ``206`` | HTTP/1.1, `RFC 2616, Section                                          |
265|                                          |         | 10.2.7                                                                |
266|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7>`_  |
267+------------------------------------------+---------+-----------------------------------------------------------------------+
268| :const:`MULTI_STATUS`                    | ``207`` | WEBDAV `RFC 2518, Section 10.2                                        |
269|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_207>`_               |
270+------------------------------------------+---------+-----------------------------------------------------------------------+
271| :const:`IM_USED`                         | ``226`` | Delta encoding in HTTP,                                               |
272|                                          |         | :rfc:`3229`, Section 10.4.1                                           |
273+------------------------------------------+---------+-----------------------------------------------------------------------+
274| :const:`MULTIPLE_CHOICES`                | ``300`` | HTTP/1.1, `RFC 2616, Section                                          |
275|                                          |         | 10.3.1                                                                |
276|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1>`_  |
277+------------------------------------------+---------+-----------------------------------------------------------------------+
278| :const:`MOVED_PERMANENTLY`               | ``301`` | HTTP/1.1, `RFC 2616, Section                                          |
279|                                          |         | 10.3.2                                                                |
280|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2>`_  |
281+------------------------------------------+---------+-----------------------------------------------------------------------+
282| :const:`FOUND`                           | ``302`` | HTTP/1.1, `RFC 2616, Section                                          |
283|                                          |         | 10.3.3                                                                |
284|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3>`_  |
285+------------------------------------------+---------+-----------------------------------------------------------------------+
286| :const:`SEE_OTHER`                       | ``303`` | HTTP/1.1, `RFC 2616, Section                                          |
287|                                          |         | 10.3.4                                                                |
288|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4>`_  |
289+------------------------------------------+---------+-----------------------------------------------------------------------+
290| :const:`NOT_MODIFIED`                    | ``304`` | HTTP/1.1, `RFC 2616, Section                                          |
291|                                          |         | 10.3.5                                                                |
292|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5>`_  |
293+------------------------------------------+---------+-----------------------------------------------------------------------+
294| :const:`USE_PROXY`                       | ``305`` | HTTP/1.1, `RFC 2616, Section                                          |
295|                                          |         | 10.3.6                                                                |
296|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.6>`_  |
297+------------------------------------------+---------+-----------------------------------------------------------------------+
298| :const:`TEMPORARY_REDIRECT`              | ``307`` | HTTP/1.1, `RFC 2616, Section                                          |
299|                                          |         | 10.3.8                                                                |
300|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8>`_  |
301+------------------------------------------+---------+-----------------------------------------------------------------------+
302| :const:`BAD_REQUEST`                     | ``400`` | HTTP/1.1, `RFC 2616, Section                                          |
303|                                          |         | 10.4.1                                                                |
304|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1>`_  |
305+------------------------------------------+---------+-----------------------------------------------------------------------+
306| :const:`UNAUTHORIZED`                    | ``401`` | HTTP/1.1, `RFC 2616, Section                                          |
307|                                          |         | 10.4.2                                                                |
308|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2>`_  |
309+------------------------------------------+---------+-----------------------------------------------------------------------+
310| :const:`PAYMENT_REQUIRED`                | ``402`` | HTTP/1.1, `RFC 2616, Section                                          |
311|                                          |         | 10.4.3                                                                |
312|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.3>`_  |
313+------------------------------------------+---------+-----------------------------------------------------------------------+
314| :const:`FORBIDDEN`                       | ``403`` | HTTP/1.1, `RFC 2616, Section                                          |
315|                                          |         | 10.4.4                                                                |
316|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4>`_  |
317+------------------------------------------+---------+-----------------------------------------------------------------------+
318| :const:`NOT_FOUND`                       | ``404`` | HTTP/1.1, `RFC 2616, Section                                          |
319|                                          |         | 10.4.5                                                                |
320|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5>`_  |
321+------------------------------------------+---------+-----------------------------------------------------------------------+
322| :const:`METHOD_NOT_ALLOWED`              | ``405`` | HTTP/1.1, `RFC 2616, Section                                          |
323|                                          |         | 10.4.6                                                                |
324|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6>`_  |
325+------------------------------------------+---------+-----------------------------------------------------------------------+
326| :const:`NOT_ACCEPTABLE`                  | ``406`` | HTTP/1.1, `RFC 2616, Section                                          |
327|                                          |         | 10.4.7                                                                |
328|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7>`_  |
329+------------------------------------------+---------+-----------------------------------------------------------------------+
330| :const:`PROXY_AUTHENTICATION_REQUIRED`   | ``407`` | HTTP/1.1, `RFC 2616, Section                                          |
331|                                          |         | 10.4.8                                                                |
332|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8>`_  |
333+------------------------------------------+---------+-----------------------------------------------------------------------+
334| :const:`REQUEST_TIMEOUT`                 | ``408`` | HTTP/1.1, `RFC 2616, Section                                          |
335|                                          |         | 10.4.9                                                                |
336|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9>`_  |
337+------------------------------------------+---------+-----------------------------------------------------------------------+
338| :const:`CONFLICT`                        | ``409`` | HTTP/1.1, `RFC 2616, Section                                          |
339|                                          |         | 10.4.10                                                               |
340|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10>`_ |
341+------------------------------------------+---------+-----------------------------------------------------------------------+
342| :const:`GONE`                            | ``410`` | HTTP/1.1, `RFC 2616, Section                                          |
343|                                          |         | 10.4.11                                                               |
344|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.11>`_ |
345+------------------------------------------+---------+-----------------------------------------------------------------------+
346| :const:`LENGTH_REQUIRED`                 | ``411`` | HTTP/1.1, `RFC 2616, Section                                          |
347|                                          |         | 10.4.12                                                               |
348|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.12>`_ |
349+------------------------------------------+---------+-----------------------------------------------------------------------+
350| :const:`PRECONDITION_FAILED`             | ``412`` | HTTP/1.1, `RFC 2616, Section                                          |
351|                                          |         | 10.4.13                                                               |
352|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.13>`_ |
353+------------------------------------------+---------+-----------------------------------------------------------------------+
354| :const:`REQUEST_ENTITY_TOO_LARGE`        | ``413`` | HTTP/1.1, `RFC 2616, Section                                          |
355|                                          |         | 10.4.14                                                               |
356|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.14>`_ |
357+------------------------------------------+---------+-----------------------------------------------------------------------+
358| :const:`REQUEST_URI_TOO_LONG`            | ``414`` | HTTP/1.1, `RFC 2616, Section                                          |
359|                                          |         | 10.4.15                                                               |
360|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15>`_ |
361+------------------------------------------+---------+-----------------------------------------------------------------------+
362| :const:`UNSUPPORTED_MEDIA_TYPE`          | ``415`` | HTTP/1.1, `RFC 2616, Section                                          |
363|                                          |         | 10.4.16                                                               |
364|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16>`_ |
365+------------------------------------------+---------+-----------------------------------------------------------------------+
366| :const:`REQUESTED_RANGE_NOT_SATISFIABLE` | ``416`` | HTTP/1.1, `RFC 2616, Section                                          |
367|                                          |         | 10.4.17                                                               |
368|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.17>`_ |
369+------------------------------------------+---------+-----------------------------------------------------------------------+
370| :const:`EXPECTATION_FAILED`              | ``417`` | HTTP/1.1, `RFC 2616, Section                                          |
371|                                          |         | 10.4.18                                                               |
372|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.18>`_ |
373+------------------------------------------+---------+-----------------------------------------------------------------------+
374| :const:`UNPROCESSABLE_ENTITY`            | ``422`` | WEBDAV, `RFC 2518, Section 10.3                                       |
375|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_422>`_               |
376+------------------------------------------+---------+-----------------------------------------------------------------------+
377| :const:`LOCKED`                          | ``423`` | WEBDAV `RFC 2518, Section 10.4                                        |
378|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_423>`_               |
379+------------------------------------------+---------+-----------------------------------------------------------------------+
380| :const:`FAILED_DEPENDENCY`               | ``424`` | WEBDAV, `RFC 2518, Section 10.5                                       |
381|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_424>`_               |
382+------------------------------------------+---------+-----------------------------------------------------------------------+
383| :const:`UPGRADE_REQUIRED`                | ``426`` | HTTP Upgrade to TLS,                                                  |
384|                                          |         | :rfc:`2817`, Section 6                                                |
385+------------------------------------------+---------+-----------------------------------------------------------------------+
386| :const:`INTERNAL_SERVER_ERROR`           | ``500`` | HTTP/1.1, `RFC 2616, Section                                          |
387|                                          |         | 10.5.1                                                                |
388|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1>`_  |
389+------------------------------------------+---------+-----------------------------------------------------------------------+
390| :const:`NOT_IMPLEMENTED`                 | ``501`` | HTTP/1.1, `RFC 2616, Section                                          |
391|                                          |         | 10.5.2                                                                |
392|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2>`_  |
393+------------------------------------------+---------+-----------------------------------------------------------------------+
394| :const:`BAD_GATEWAY`                     | ``502`` | HTTP/1.1 `RFC 2616, Section                                           |
395|                                          |         | 10.5.3                                                                |
396|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3>`_  |
397+------------------------------------------+---------+-----------------------------------------------------------------------+
398| :const:`SERVICE_UNAVAILABLE`             | ``503`` | HTTP/1.1, `RFC 2616, Section                                          |
399|                                          |         | 10.5.4                                                                |
400|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4>`_  |
401+------------------------------------------+---------+-----------------------------------------------------------------------+
402| :const:`GATEWAY_TIMEOUT`                 | ``504`` | HTTP/1.1 `RFC 2616, Section                                           |
403|                                          |         | 10.5.5                                                                |
404|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5>`_  |
405+------------------------------------------+---------+-----------------------------------------------------------------------+
406| :const:`HTTP_VERSION_NOT_SUPPORTED`      | ``505`` | HTTP/1.1, `RFC 2616, Section                                          |
407|                                          |         | 10.5.6                                                                |
408|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.6>`_  |
409+------------------------------------------+---------+-----------------------------------------------------------------------+
410| :const:`INSUFFICIENT_STORAGE`            | ``507`` | WEBDAV, `RFC 2518, Section 10.6                                       |
411|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_507>`_               |
412+------------------------------------------+---------+-----------------------------------------------------------------------+
413| :const:`NOT_EXTENDED`                    | ``510`` | An HTTP Extension Framework,                                          |
414|                                          |         | :rfc:`2774`, Section 7                                                |
415+------------------------------------------+---------+-----------------------------------------------------------------------+
416
417
418.. data:: responses
419
420   This dictionary maps the HTTP 1.1 status codes to the W3C names.
421
422   Example: ``httplib.responses[httplib.NOT_FOUND]`` is ``'Not Found'``.
423
424   .. versionadded:: 2.5
425
426
427.. _httpconnection-objects:
428
429HTTPConnection Objects
430----------------------
431
432:class:`HTTPConnection` instances have the following methods:
433
434
435.. method:: HTTPConnection.request(method, url[, body[, headers]])
436
437   This will send a request to the server using the HTTP request method *method*
438   and the selector *url*.  If the *body* argument is present, it should be a
439   string of data to send after the headers are finished. Alternatively, it may
440   be an open file object, in which case the contents of the file is sent; this
441   file object should support ``fileno()`` and ``read()`` methods. The
442   *headers* argument should be a mapping of extra HTTP headers to send with
443   the request.
444
445   If one is not provided in *headers*, a ``Content-Length`` header is added
446   automatically for all methods if the length of the body can be determined,
447   either from the length of the ``str`` representation, or from the reported
448   size of the file on disk. If *body* is ``None`` the header is not set except
449   for methods that expect a body (``PUT``, ``POST``, and ``PATCH``) in which
450   case it is set to ``0``.
451
452   .. versionchanged:: 2.6
453      *body* can be a file object.
454
455
456.. method:: HTTPConnection.getresponse()
457
458   Should be called after a request is sent to get the response from the server.
459   Returns an :class:`HTTPResponse` instance.
460
461   .. note::
462
463      Note that you must have read the whole response before you can send a new
464      request to the server.
465
466
467.. method:: HTTPConnection.set_debuglevel(level)
468
469   Set the debugging level (the amount of debugging output printed). The default
470   debug level is ``0``, meaning no debugging output is printed.
471
472
473.. method:: HTTPConnection.set_tunnel(host,port=None, headers=None)
474
475   Set the host and the port for HTTP Connect Tunnelling. Normally used when
476   it is required to do HTTPS Conection through a proxy server.
477
478   The headers argument should be a mapping of extra HTTP headers to send
479   with the CONNECT request.
480
481   .. versionadded:: 2.7
482
483
484.. method:: HTTPConnection.connect()
485
486   Connect to the server specified when the object was created.
487
488
489.. method:: HTTPConnection.close()
490
491   Close the connection to the server.
492
493As an alternative to using the :meth:`request` method described above, you can
494also send your request step by step, by using the four functions below.
495
496
497.. method:: HTTPConnection.putrequest(request, selector[, skip_host[, skip_accept_encoding]])
498
499   This should be the first call after the connection to the server has been made.
500   It sends a line to the server consisting of the *request* string, the *selector*
501   string, and the HTTP version (``HTTP/1.1``).  To disable automatic sending of
502   ``Host:`` or ``Accept-Encoding:`` headers (for example to accept additional
503   content encodings), specify *skip_host* or *skip_accept_encoding* with non-False
504   values.
505
506   .. versionchanged:: 2.4
507      *skip_accept_encoding* argument added.
508
509
510.. method:: HTTPConnection.putheader(header, argument[, ...])
511
512   Send an :rfc:`822`\ -style header to the server.  It sends a line to the server
513   consisting of the header, a colon and a space, and the first argument.  If more
514   arguments are given, continuation lines are sent, each consisting of a tab and
515   an argument.
516
517
518.. method:: HTTPConnection.endheaders(message_body=None)
519
520   Send a blank line to the server, signalling the end of the headers. The
521   optional *message_body* argument can be used to pass a message body
522   associated with the request.  The message body will be sent in the same
523   packet as the message headers if it is string, otherwise it is sent in a
524   separate packet.
525
526   .. versionchanged:: 2.7
527      *message_body* was added.
528
529
530.. method:: HTTPConnection.send(data)
531
532   Send data to the server.  This should be used directly only after the
533   :meth:`endheaders` method has been called and before :meth:`getresponse` is
534   called.
535
536
537.. _httpresponse-objects:
538
539HTTPResponse Objects
540--------------------
541
542:class:`HTTPResponse` instances have the following methods and attributes:
543
544
545.. method:: HTTPResponse.read([amt])
546
547   Reads and returns the response body, or up to the next *amt* bytes.
548
549
550.. method:: HTTPResponse.getheader(name[, default])
551
552   Get the contents of the header *name*, or *default* if there is no matching
553   header.
554
555
556.. method:: HTTPResponse.getheaders()
557
558   Return a list of (header, value) tuples.
559
560   .. versionadded:: 2.4
561
562.. method:: HTTPResponse.fileno()
563
564   Returns the ``fileno`` of the underlying socket.
565
566.. attribute:: HTTPResponse.msg
567
568   A :class:`mimetools.Message` instance containing the response headers.
569
570
571.. attribute:: HTTPResponse.version
572
573   HTTP protocol version used by server.  10 for HTTP/1.0, 11 for HTTP/1.1.
574
575
576.. attribute:: HTTPResponse.status
577
578   Status code returned by server.
579
580
581.. attribute:: HTTPResponse.reason
582
583   Reason phrase returned by server.
584
585
586.. _httplib-examples:
587
588Examples
589--------
590
591Here is an example session that uses the ``GET`` method::
592
593   >>> import httplib
594   >>> conn = httplib.HTTPSConnection("www.python.org")
595   >>> conn.request("GET", "/")
596   >>> r1 = conn.getresponse()
597   >>> print r1.status, r1.reason
598   200 OK
599   >>> data1 = r1.read()
600   >>> conn.request("GET", "/")
601   >>> r2 = conn.getresponse()
602   >>> print r2.status, r2.reason
603   404 Not Found
604   >>> data2 = r2.read()
605   >>> conn.close()
606
607Here is an example session that uses the ``HEAD`` method.  Note that the
608``HEAD`` method never returns any data. ::
609
610   >>> import httplib
611   >>> conn = httplib.HTTPSConnection("www.python.org")
612   >>> conn.request("HEAD","/")
613   >>> res = conn.getresponse()
614   >>> print res.status, res.reason
615   200 OK
616   >>> data = res.read()
617   >>> print len(data)
618   0
619   >>> data == ''
620   True
621
622Here is an example session that shows how to ``POST`` requests::
623
624   >>> import httplib, urllib
625   >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
626   >>> headers = {"Content-type": "application/x-www-form-urlencoded",
627   ...            "Accept": "text/plain"}
628   >>> conn = httplib.HTTPConnection("bugs.python.org")
629   >>> conn.request("POST", "", params, headers)
630   >>> response = conn.getresponse()
631   >>> print response.status, response.reason
632   302 Found
633   >>> data = response.read()
634   >>> data
635   'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
636   >>> conn.close()
637
638Client side ``HTTP PUT`` requests are very similar to ``POST`` requests. The
639difference lies only the server side where HTTP server will allow resources to
640be created via ``PUT`` request. Here is an example session that shows how to do
641``PUT`` request using httplib::
642
643    >>> # This creates an HTTP message
644    >>> # with the content of BODY as the enclosed representation
645    >>> # for the resource http://localhost:8080/foobar
646    ...
647    >>> import httplib
648    >>> BODY = "***filecontents***"
649    >>> conn = httplib.HTTPConnection("localhost", 8080)
650    >>> conn.request("PUT", "/file", BODY)
651    >>> response = conn.getresponse()
652    >>> print response.status, response.reason
653    200, OK
654
655