1 :mod:`httplib` --- HTTP protocol client
2 =======================================
5 :synopsis: HTTP and HTTPS protocol client (requires sockets).
8 The :mod:`httplib` module has been renamed to :mod:`http.client` in Python
9 3.0. The :term:`2to3` tool will automatically adapt imports when converting
15 single: HTTP; httplib (standard module)
17 .. index:: module: urllib
19 This module defines classes which implement the client side of the HTTP and
20 HTTPS protocols. It is normally not used directly --- the module :mod:`urllib`
21 uses it to handle URLs that use HTTP and HTTPS.
25 HTTPS support is only available if the :mod:`socket` module was compiled with
30 The public interface for this module changed substantially in Python 2.0. The
31 :class:`HTTP` class is retained only for backward compatibility with 1.5.2. It
32 should not be used in new code. Refer to the online docstrings for usage.
34 The module provides the following classes:
37 .. class:: HTTPConnection(host[, port[, strict[, timeout[, source_address]]]])
39 An :class:`HTTPConnection` instance represents one transaction with an HTTP
40 server. It should be instantiated passing it a host and optional port
41 number. If no port number is passed, the port is extracted from the host
42 string if it has the form ``host:port``, else the default HTTP port (80) is
43 used. When True, the optional parameter *strict* (which defaults to a false
44 value) causes ``BadStatusLine`` to
45 be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1
46 status line. If the optional *timeout* parameter is given, blocking
47 operations (like connection attempts) will timeout after that many seconds
48 (if it is not given, the global default timeout setting is used).
49 The optional *source_address* parameter may be a tuple of a (host, port)
50 to use as the source address the HTTP connection is made from.
52 For example, the following calls all create instances that connect to the server
53 at the same host and port::
55 >>> h1 = httplib.HTTPConnection('www.cwi.nl')
56 >>> h2 = httplib.HTTPConnection('www.cwi.nl:80')
57 >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80)
58 >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10)
62 .. versionchanged:: 2.6
65 .. versionchanged:: 2.7
66 *source_address* was added.
69 .. class:: HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout[, source_address]]]]]])
71 A subclass of :class:`HTTPConnection` that uses SSL for communication with
72 secure servers. Default port is ``443``. *key_file* is the name of a PEM
73 formatted file that contains your private key. *cert_file* is a PEM formatted
74 certificate chain file.
78 This does not do any certificate verification.
82 .. versionchanged:: 2.6
85 .. versionchanged:: 2.7
86 *source_address* was added.
89 .. class:: HTTPResponse(sock[, debuglevel=0][, strict=0])
91 Class whose instances are returned upon successful connection. Not instantiated
96 The following exceptions are raised as appropriate:
99 .. exception:: HTTPException
101 The base class of the other exceptions in this module. It is a subclass of
104 .. versionadded:: 2.0
107 .. exception:: NotConnected
109 A subclass of :exc:`HTTPException`.
111 .. versionadded:: 2.0
114 .. exception:: InvalidURL
116 A subclass of :exc:`HTTPException`, raised if a port is given and is either
117 non-numeric or empty.
119 .. versionadded:: 2.3
122 .. exception:: UnknownProtocol
124 A subclass of :exc:`HTTPException`.
126 .. versionadded:: 2.0
129 .. exception:: UnknownTransferEncoding
131 A subclass of :exc:`HTTPException`.
133 .. versionadded:: 2.0
136 .. exception:: UnimplementedFileMode
138 A subclass of :exc:`HTTPException`.
140 .. versionadded:: 2.0
143 .. exception:: IncompleteRead
145 A subclass of :exc:`HTTPException`.
147 .. versionadded:: 2.0
150 .. exception:: ImproperConnectionState
152 A subclass of :exc:`HTTPException`.
154 .. versionadded:: 2.0
157 .. exception:: CannotSendRequest
159 A subclass of :exc:`ImproperConnectionState`.
161 .. versionadded:: 2.0
164 .. exception:: CannotSendHeader
166 A subclass of :exc:`ImproperConnectionState`.
168 .. versionadded:: 2.0
171 .. exception:: ResponseNotReady
173 A subclass of :exc:`ImproperConnectionState`.
175 .. versionadded:: 2.0
178 .. exception:: BadStatusLine
180 A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP
181 status code that we don't understand.
183 .. versionadded:: 2.0
185 The constants defined in this module are:
190 The default port for the HTTP protocol (always ``80``).
195 The default port for the HTTPS protocol (always ``443``).
197 and also the following constants for integer status codes:
199 +------------------------------------------+---------+-----------------------------------------------------------------------+
200 | Constant | Value | Definition |
201 +==========================================+=========+=======================================================================+
202 | :const:`CONTINUE` | ``100`` | HTTP/1.1, `RFC 2616, Section |
204 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1>`_ |
205 +------------------------------------------+---------+-----------------------------------------------------------------------+
206 | :const:`SWITCHING_PROTOCOLS` | ``101`` | HTTP/1.1, `RFC 2616, Section |
208 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.2>`_ |
209 +------------------------------------------+---------+-----------------------------------------------------------------------+
210 | :const:`PROCESSING` | ``102`` | WEBDAV, `RFC 2518, Section 10.1 |
211 | | | <http://www.webdav.org/specs/rfc2518.html#STATUS_102>`_ |
212 +------------------------------------------+---------+-----------------------------------------------------------------------+
213 | :const:`OK` | ``200`` | HTTP/1.1, `RFC 2616, Section |
215 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1>`_ |
216 +------------------------------------------+---------+-----------------------------------------------------------------------+
217 | :const:`CREATED` | ``201`` | HTTP/1.1, `RFC 2616, Section |
219 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2>`_ |
220 +------------------------------------------+---------+-----------------------------------------------------------------------+
221 | :const:`ACCEPTED` | ``202`` | HTTP/1.1, `RFC 2616, Section |
223 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3>`_ |
224 +------------------------------------------+---------+-----------------------------------------------------------------------+
225 | :const:`NON_AUTHORITATIVE_INFORMATION` | ``203`` | HTTP/1.1, `RFC 2616, Section |
227 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.4>`_ |
228 +------------------------------------------+---------+-----------------------------------------------------------------------+
229 | :const:`NO_CONTENT` | ``204`` | HTTP/1.1, `RFC 2616, Section |
231 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5>`_ |
232 +------------------------------------------+---------+-----------------------------------------------------------------------+
233 | :const:`RESET_CONTENT` | ``205`` | HTTP/1.1, `RFC 2616, Section |
235 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.6>`_ |
236 +------------------------------------------+---------+-----------------------------------------------------------------------+
237 | :const:`PARTIAL_CONTENT` | ``206`` | HTTP/1.1, `RFC 2616, Section |
239 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7>`_ |
240 +------------------------------------------+---------+-----------------------------------------------------------------------+
241 | :const:`MULTI_STATUS` | ``207`` | WEBDAV `RFC 2518, Section 10.2 |
242 | | | <http://www.webdav.org/specs/rfc2518.html#STATUS_207>`_ |
243 +------------------------------------------+---------+-----------------------------------------------------------------------+
244 | :const:`IM_USED` | ``226`` | Delta encoding in HTTP, |
245 | | | :rfc:`3229`, Section 10.4.1 |
246 +------------------------------------------+---------+-----------------------------------------------------------------------+
247 | :const:`MULTIPLE_CHOICES` | ``300`` | HTTP/1.1, `RFC 2616, Section |
249 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1>`_ |
250 +------------------------------------------+---------+-----------------------------------------------------------------------+
251 | :const:`MOVED_PERMANENTLY` | ``301`` | HTTP/1.1, `RFC 2616, Section |
253 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2>`_ |
254 +------------------------------------------+---------+-----------------------------------------------------------------------+
255 | :const:`FOUND` | ``302`` | HTTP/1.1, `RFC 2616, Section |
257 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3>`_ |
258 +------------------------------------------+---------+-----------------------------------------------------------------------+
259 | :const:`SEE_OTHER` | ``303`` | HTTP/1.1, `RFC 2616, Section |
261 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4>`_ |
262 +------------------------------------------+---------+-----------------------------------------------------------------------+
263 | :const:`NOT_MODIFIED` | ``304`` | HTTP/1.1, `RFC 2616, Section |
265 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5>`_ |
266 +------------------------------------------+---------+-----------------------------------------------------------------------+
267 | :const:`USE_PROXY` | ``305`` | HTTP/1.1, `RFC 2616, Section |
269 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.6>`_ |
270 +------------------------------------------+---------+-----------------------------------------------------------------------+
271 | :const:`TEMPORARY_REDIRECT` | ``307`` | HTTP/1.1, `RFC 2616, Section |
273 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8>`_ |
274 +------------------------------------------+---------+-----------------------------------------------------------------------+
275 | :const:`BAD_REQUEST` | ``400`` | HTTP/1.1, `RFC 2616, Section |
277 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1>`_ |
278 +------------------------------------------+---------+-----------------------------------------------------------------------+
279 | :const:`UNAUTHORIZED` | ``401`` | HTTP/1.1, `RFC 2616, Section |
281 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2>`_ |
282 +------------------------------------------+---------+-----------------------------------------------------------------------+
283 | :const:`PAYMENT_REQUIRED` | ``402`` | HTTP/1.1, `RFC 2616, Section |
285 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.3>`_ |
286 +------------------------------------------+---------+-----------------------------------------------------------------------+
287 | :const:`FORBIDDEN` | ``403`` | HTTP/1.1, `RFC 2616, Section |
289 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4>`_ |
290 +------------------------------------------+---------+-----------------------------------------------------------------------+
291 | :const:`NOT_FOUND` | ``404`` | HTTP/1.1, `RFC 2616, Section |
293 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5>`_ |
294 +------------------------------------------+---------+-----------------------------------------------------------------------+
295 | :const:`METHOD_NOT_ALLOWED` | ``405`` | HTTP/1.1, `RFC 2616, Section |
297 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6>`_ |
298 +------------------------------------------+---------+-----------------------------------------------------------------------+
299 | :const:`NOT_ACCEPTABLE` | ``406`` | HTTP/1.1, `RFC 2616, Section |
301 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7>`_ |
302 +------------------------------------------+---------+-----------------------------------------------------------------------+
303 | :const:`PROXY_AUTHENTICATION_REQUIRED` | ``407`` | HTTP/1.1, `RFC 2616, Section |
305 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8>`_ |
306 +------------------------------------------+---------+-----------------------------------------------------------------------+
307 | :const:`REQUEST_TIMEOUT` | ``408`` | HTTP/1.1, `RFC 2616, Section |
309 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9>`_ |
310 +------------------------------------------+---------+-----------------------------------------------------------------------+
311 | :const:`CONFLICT` | ``409`` | HTTP/1.1, `RFC 2616, Section |
313 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10>`_ |
314 +------------------------------------------+---------+-----------------------------------------------------------------------+
315 | :const:`GONE` | ``410`` | HTTP/1.1, `RFC 2616, Section |
317 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.11>`_ |
318 +------------------------------------------+---------+-----------------------------------------------------------------------+
319 | :const:`LENGTH_REQUIRED` | ``411`` | HTTP/1.1, `RFC 2616, Section |
321 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.12>`_ |
322 +------------------------------------------+---------+-----------------------------------------------------------------------+
323 | :const:`PRECONDITION_FAILED` | ``412`` | HTTP/1.1, `RFC 2616, Section |
325 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.13>`_ |
326 +------------------------------------------+---------+-----------------------------------------------------------------------+
327 | :const:`REQUEST_ENTITY_TOO_LARGE` | ``413`` | HTTP/1.1, `RFC 2616, Section |
329 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.14>`_ |
330 +------------------------------------------+---------+-----------------------------------------------------------------------+
331 | :const:`REQUEST_URI_TOO_LONG` | ``414`` | HTTP/1.1, `RFC 2616, Section |
333 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15>`_ |
334 +------------------------------------------+---------+-----------------------------------------------------------------------+
335 | :const:`UNSUPPORTED_MEDIA_TYPE` | ``415`` | HTTP/1.1, `RFC 2616, Section |
337 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16>`_ |
338 +------------------------------------------+---------+-----------------------------------------------------------------------+
339 | :const:`REQUESTED_RANGE_NOT_SATISFIABLE` | ``416`` | HTTP/1.1, `RFC 2616, Section |
341 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.17>`_ |
342 +------------------------------------------+---------+-----------------------------------------------------------------------+
343 | :const:`EXPECTATION_FAILED` | ``417`` | HTTP/1.1, `RFC 2616, Section |
345 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.18>`_ |
346 +------------------------------------------+---------+-----------------------------------------------------------------------+
347 | :const:`UNPROCESSABLE_ENTITY` | ``422`` | WEBDAV, `RFC 2518, Section 10.3 |
348 | | | <http://www.webdav.org/specs/rfc2518.html#STATUS_422>`_ |
349 +------------------------------------------+---------+-----------------------------------------------------------------------+
350 | :const:`LOCKED` | ``423`` | WEBDAV `RFC 2518, Section 10.4 |
351 | | | <http://www.webdav.org/specs/rfc2518.html#STATUS_423>`_ |
352 +------------------------------------------+---------+-----------------------------------------------------------------------+
353 | :const:`FAILED_DEPENDENCY` | ``424`` | WEBDAV, `RFC 2518, Section 10.5 |
354 | | | <http://www.webdav.org/specs/rfc2518.html#STATUS_424>`_ |
355 +------------------------------------------+---------+-----------------------------------------------------------------------+
356 | :const:`UPGRADE_REQUIRED` | ``426`` | HTTP Upgrade to TLS, |
357 | | | :rfc:`2817`, Section 6 |
358 +------------------------------------------+---------+-----------------------------------------------------------------------+
359 | :const:`INTERNAL_SERVER_ERROR` | ``500`` | HTTP/1.1, `RFC 2616, Section |
361 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1>`_ |
362 +------------------------------------------+---------+-----------------------------------------------------------------------+
363 | :const:`NOT_IMPLEMENTED` | ``501`` | HTTP/1.1, `RFC 2616, Section |
365 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2>`_ |
366 +------------------------------------------+---------+-----------------------------------------------------------------------+
367 | :const:`BAD_GATEWAY` | ``502`` | HTTP/1.1 `RFC 2616, Section |
369 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3>`_ |
370 +------------------------------------------+---------+-----------------------------------------------------------------------+
371 | :const:`SERVICE_UNAVAILABLE` | ``503`` | HTTP/1.1, `RFC 2616, Section |
373 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4>`_ |
374 +------------------------------------------+---------+-----------------------------------------------------------------------+
375 | :const:`GATEWAY_TIMEOUT` | ``504`` | HTTP/1.1 `RFC 2616, Section |
377 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5>`_ |
378 +------------------------------------------+---------+-----------------------------------------------------------------------+
379 | :const:`HTTP_VERSION_NOT_SUPPORTED` | ``505`` | HTTP/1.1, `RFC 2616, Section |
381 | | | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.6>`_ |
382 +------------------------------------------+---------+-----------------------------------------------------------------------+
383 | :const:`INSUFFICIENT_STORAGE` | ``507`` | WEBDAV, `RFC 2518, Section 10.6 |
384 | | | <http://www.webdav.org/specs/rfc2518.html#STATUS_507>`_ |
385 +------------------------------------------+---------+-----------------------------------------------------------------------+
386 | :const:`NOT_EXTENDED` | ``510`` | An HTTP Extension Framework, |
387 | | | :rfc:`2774`, Section 7 |
388 +------------------------------------------+---------+-----------------------------------------------------------------------+
393 This dictionary maps the HTTP 1.1 status codes to the W3C names.
395 Example: ``httplib.responses[httplib.NOT_FOUND]`` is ``'Not Found'``.
397 .. versionadded:: 2.5
400 .. _httpconnection-objects:
402 HTTPConnection Objects
403 ----------------------
405 :class:`HTTPConnection` instances have the following methods:
408 .. method:: HTTPConnection.request(method, url[, body[, headers]])
410 This will send a request to the server using the HTTP request method *method*
411 and the selector *url*. If the *body* argument is present, it should be a
412 string of data to send after the headers are finished. Alternatively, it may
413 be an open file object, in which case the contents of the file is sent; this
414 file object should support ``fileno()`` and ``read()`` methods. The header
415 Content-Length is automatically set to the correct value. The *headers*
416 argument should be a mapping of extra HTTP headers to send with the request.
418 .. versionchanged:: 2.6
419 *body* can be a file object.
422 .. method:: HTTPConnection.getresponse()
424 Should be called after a request is sent to get the response from the server.
425 Returns an :class:`HTTPResponse` instance.
429 Note that you must have read the whole response before you can send a new
430 request to the server.
433 .. method:: HTTPConnection.set_debuglevel(level)
435 Set the debugging level (the amount of debugging output printed). The default
436 debug level is ``0``, meaning no debugging output is printed.
439 .. method:: HTTPConnection.set_tunnel(host,port=None, headers=None)
441 Set the host and the port for HTTP Connect Tunnelling. Normally used when
442 it is required to do HTTPS Conection through a proxy server.
444 The headers argument should be a mapping of extra HTTP headers to to sent
445 with the CONNECT request.
447 .. versionadded:: 2.7
450 .. method:: HTTPConnection.connect()
452 Connect to the server specified when the object was created.
455 .. method:: HTTPConnection.close()
457 Close the connection to the server.
459 As an alternative to using the :meth:`request` method described above, you can
460 also send your request step by step, by using the four functions below.
463 .. method:: HTTPConnection.putrequest(request, selector[, skip_host[, skip_accept_encoding]])
465 This should be the first call after the connection to the server has been made.
466 It sends a line to the server consisting of the *request* string, the *selector*
467 string, and the HTTP version (``HTTP/1.1``). To disable automatic sending of
468 ``Host:`` or ``Accept-Encoding:`` headers (for example to accept additional
469 content encodings), specify *skip_host* or *skip_accept_encoding* with non-False
472 .. versionchanged:: 2.4
473 *skip_accept_encoding* argument added.
476 .. method:: HTTPConnection.putheader(header, argument[, ...])
478 Send an :rfc:`822`\ -style header to the server. It sends a line to the server
479 consisting of the header, a colon and a space, and the first argument. If more
480 arguments are given, continuation lines are sent, each consisting of a tab and
484 .. method:: HTTPConnection.endheaders()
486 Send a blank line to the server, signalling the end of the headers.
489 .. method:: HTTPConnection.send(data)
491 Send data to the server. This should be used directly only after the
492 :meth:`endheaders` method has been called and before :meth:`getresponse` is
496 .. _httpresponse-objects:
501 :class:`HTTPResponse` instances have the following methods and attributes:
504 .. method:: HTTPResponse.read([amt])
506 Reads and returns the response body, or up to the next *amt* bytes.
509 .. method:: HTTPResponse.getheader(name[, default])
511 Get the contents of the header *name*, or *default* if there is no matching
515 .. method:: HTTPResponse.getheaders()
517 Return a list of (header, value) tuples.
519 .. versionadded:: 2.4
522 .. attribute:: HTTPResponse.msg
524 A :class:`mimetools.Message` instance containing the response headers.
527 .. attribute:: HTTPResponse.version
529 HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.
532 .. attribute:: HTTPResponse.status
534 Status code returned by server.
537 .. attribute:: HTTPResponse.reason
539 Reason phrase returned by server.
542 .. _httplib-examples:
547 Here is an example session that uses the ``GET`` method::
550 >>> conn = httplib.HTTPConnection("www.python.org")
551 >>> conn.request("GET", "/index.html")
552 >>> r1 = conn.getresponse()
553 >>> print r1.status, r1.reason
555 >>> data1 = r1.read()
556 >>> conn.request("GET", "/parrot.spam")
557 >>> r2 = conn.getresponse()
558 >>> print r2.status, r2.reason
560 >>> data2 = r2.read()
563 Here is an example session that shows how to ``POST`` requests::
565 >>> import httplib, urllib
566 >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
567 >>> headers = {"Content-type": "application/x-www-form-urlencoded",
568 ... "Accept": "text/plain"}
569 >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
570 >>> conn.request("POST", "/cgi-bin/query", params, headers)
571 >>> response = conn.getresponse()
572 >>> print response.status, response.reason
574 >>> data = response.read()