cpython/Doc/library/http.client.rst

614 lines
20 KiB
ReStructuredText
Raw Normal View History

2008-05-26 13:32:26 -03:00
:mod:`http.client` --- HTTP protocol client
===========================================
2007-08-15 11:28:22 -03:00
2008-05-26 13:32:26 -03:00
.. module:: http.client
2007-08-15 11:28:22 -03:00
:synopsis: HTTP and HTTPS protocol client (requires sockets).
**Source code:** :source:`Lib/http/client.py`
2007-08-15 11:28:22 -03:00
.. index::
pair: HTTP; protocol
2008-05-26 13:32:26 -03:00
single: HTTP; http.client (standard module)
2007-08-15 11:28:22 -03:00
.. index:: module: urllib.request
2007-08-15 11:28:22 -03:00
2011-01-27 16:38:46 -04:00
--------------
2007-08-15 11:28:22 -03:00
This module defines classes which implement the client side of the HTTP and
HTTPS protocols. It is normally not used directly --- the module
:mod:`urllib.request` uses it to handle URLs that use HTTP and HTTPS.
2007-08-15 11:28:22 -03:00
.. seealso::
The `Requests package <https://requests.readthedocs.io/en/master/>`_
is recommended for a higher-level HTTP client interface.
2007-08-15 11:28:22 -03:00
.. note::
2010-10-13 07:39:21 -03:00
HTTPS support is only available if Python was compiled with SSL support
(through the :mod:`ssl` module).
2007-08-15 11:28:22 -03:00
The module provides the following classes:
.. class:: HTTPConnection(host, port=None[, timeout], source_address=None, \
blocksize=8192)
2007-08-15 11:28:22 -03:00
An :class:`HTTPConnection` instance represents one transaction with an HTTP
Merged revisions 62998-63003,63005-63006,63009-63012,63014-63017,63019-63020,63022-63024,63026-63029,63031-63041,63043-63045,63047-63054,63056-63062 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r62998 | andrew.kuchling | 2008-05-10 15:51:55 -0400 (Sat, 10 May 2008) | 7 lines #1858 from Tarek Ziade: Allow multiple repositories in .pypirc; see http://wiki.python.org/moin/EnhancedPyPI for discussion. The patch is slightly revised from Tarek's last patch: I've simplified the PyPIRCCommand.finalize_options() method to not look at sys.argv. Tests still pass. ........ r63000 | alexandre.vassalotti | 2008-05-10 15:59:16 -0400 (Sat, 10 May 2008) | 5 lines Cleaned up io._BytesIO.write(). I am amazed that the old code, for inserting null-bytes, actually worked. Who wrote that thing? Oh, it is me... doh. ........ r63002 | brett.cannon | 2008-05-10 16:52:01 -0400 (Sat, 10 May 2008) | 2 lines Revert r62998 as it broke the build (seems distutils.config is missing). ........ r63014 | andrew.kuchling | 2008-05-10 18:12:38 -0400 (Sat, 10 May 2008) | 1 line #1858: add distutils.config module ........ r63027 | brett.cannon | 2008-05-10 21:09:32 -0400 (Sat, 10 May 2008) | 2 lines Flesh out the 3.0 deprecation to suggest using the ctypes module. ........ r63028 | skip.montanaro | 2008-05-10 22:59:30 -0400 (Sat, 10 May 2008) | 4 lines Copied two versions of the example from the interactive session. Delete one. ........ r63037 | georg.brandl | 2008-05-11 03:02:17 -0400 (Sun, 11 May 2008) | 2 lines reload() takes the module itself. ........ r63038 | alexandre.vassalotti | 2008-05-11 03:06:04 -0400 (Sun, 11 May 2008) | 4 lines Added test framework for handling module renames. Factored the import guard in test_py3kwarn.TestStdlibRemovals into a context manager, namely test_support.CleanImport. ........ r63039 | georg.brandl | 2008-05-11 03:06:05 -0400 (Sun, 11 May 2008) | 2 lines #2742: ``''`` is not converted to NULL in getaddrinfo. ........ r63040 | alexandre.vassalotti | 2008-05-11 03:08:12 -0400 (Sun, 11 May 2008) | 2 lines Fixed typo in a comment of test_support.CleanImport. ........ r63041 | alexandre.vassalotti | 2008-05-11 03:10:25 -0400 (Sun, 11 May 2008) | 2 lines Removed a dead line of code. ........ r63043 | georg.brandl | 2008-05-11 04:47:53 -0400 (Sun, 11 May 2008) | 2 lines #2812: document property.getter/setter/deleter. ........ r63049 | georg.brandl | 2008-05-11 05:06:30 -0400 (Sun, 11 May 2008) | 2 lines #1153769: document PEP 237 changes to string formatting. ........ r63050 | georg.brandl | 2008-05-11 05:11:40 -0400 (Sun, 11 May 2008) | 2 lines #2809: elaborate str.split docstring a bit. ........ r63051 | georg.brandl | 2008-05-11 06:13:59 -0400 (Sun, 11 May 2008) | 2 lines Fix typo. ........ r63052 | georg.brandl | 2008-05-11 06:33:27 -0400 (Sun, 11 May 2008) | 2 lines #2709: clarification. ........ r63053 | georg.brandl | 2008-05-11 06:42:28 -0400 (Sun, 11 May 2008) | 2 lines #2659: add ``break_on_hyphens`` to TextWrapper. ........ r63057 | georg.brandl | 2008-05-11 06:59:39 -0400 (Sun, 11 May 2008) | 2 lines #2741: clarification of value range for address_family. ........ r63058 | georg.brandl | 2008-05-11 07:09:35 -0400 (Sun, 11 May 2008) | 2 lines #2452: timeout is used for all blocking operations. ........ r63059 | andrew.kuchling | 2008-05-11 09:33:56 -0400 (Sun, 11 May 2008) | 2 lines #1792: Improve performance of marshal.dumps() on large objects by increasing the size of the buffer more quickly. ........ r63060 | andrew.kuchling | 2008-05-11 10:00:00 -0400 (Sun, 11 May 2008) | 1 line #1858: re-apply patch for this, adding the missing files ........ r63061 | benjamin.peterson | 2008-05-11 10:13:25 -0400 (Sun, 11 May 2008) | 2 lines Add the "until" command to pdb ........ r63062 | georg.brandl | 2008-05-11 10:17:13 -0400 (Sun, 11 May 2008) | 2 lines Add some sentence endings. ........
2008-05-15 21:03:33 -03:00
server. It should be instantiated passing it a host and optional port
number. If no port number is passed, the port is extracted from the host
string if it has the form ``host:port``, else the default HTTP port (80) is
used. If the optional *timeout* parameter is given, blocking
Merged revisions 62998-63003,63005-63006,63009-63012,63014-63017,63019-63020,63022-63024,63026-63029,63031-63041,63043-63045,63047-63054,63056-63062 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r62998 | andrew.kuchling | 2008-05-10 15:51:55 -0400 (Sat, 10 May 2008) | 7 lines #1858 from Tarek Ziade: Allow multiple repositories in .pypirc; see http://wiki.python.org/moin/EnhancedPyPI for discussion. The patch is slightly revised from Tarek's last patch: I've simplified the PyPIRCCommand.finalize_options() method to not look at sys.argv. Tests still pass. ........ r63000 | alexandre.vassalotti | 2008-05-10 15:59:16 -0400 (Sat, 10 May 2008) | 5 lines Cleaned up io._BytesIO.write(). I am amazed that the old code, for inserting null-bytes, actually worked. Who wrote that thing? Oh, it is me... doh. ........ r63002 | brett.cannon | 2008-05-10 16:52:01 -0400 (Sat, 10 May 2008) | 2 lines Revert r62998 as it broke the build (seems distutils.config is missing). ........ r63014 | andrew.kuchling | 2008-05-10 18:12:38 -0400 (Sat, 10 May 2008) | 1 line #1858: add distutils.config module ........ r63027 | brett.cannon | 2008-05-10 21:09:32 -0400 (Sat, 10 May 2008) | 2 lines Flesh out the 3.0 deprecation to suggest using the ctypes module. ........ r63028 | skip.montanaro | 2008-05-10 22:59:30 -0400 (Sat, 10 May 2008) | 4 lines Copied two versions of the example from the interactive session. Delete one. ........ r63037 | georg.brandl | 2008-05-11 03:02:17 -0400 (Sun, 11 May 2008) | 2 lines reload() takes the module itself. ........ r63038 | alexandre.vassalotti | 2008-05-11 03:06:04 -0400 (Sun, 11 May 2008) | 4 lines Added test framework for handling module renames. Factored the import guard in test_py3kwarn.TestStdlibRemovals into a context manager, namely test_support.CleanImport. ........ r63039 | georg.brandl | 2008-05-11 03:06:05 -0400 (Sun, 11 May 2008) | 2 lines #2742: ``''`` is not converted to NULL in getaddrinfo. ........ r63040 | alexandre.vassalotti | 2008-05-11 03:08:12 -0400 (Sun, 11 May 2008) | 2 lines Fixed typo in a comment of test_support.CleanImport. ........ r63041 | alexandre.vassalotti | 2008-05-11 03:10:25 -0400 (Sun, 11 May 2008) | 2 lines Removed a dead line of code. ........ r63043 | georg.brandl | 2008-05-11 04:47:53 -0400 (Sun, 11 May 2008) | 2 lines #2812: document property.getter/setter/deleter. ........ r63049 | georg.brandl | 2008-05-11 05:06:30 -0400 (Sun, 11 May 2008) | 2 lines #1153769: document PEP 237 changes to string formatting. ........ r63050 | georg.brandl | 2008-05-11 05:11:40 -0400 (Sun, 11 May 2008) | 2 lines #2809: elaborate str.split docstring a bit. ........ r63051 | georg.brandl | 2008-05-11 06:13:59 -0400 (Sun, 11 May 2008) | 2 lines Fix typo. ........ r63052 | georg.brandl | 2008-05-11 06:33:27 -0400 (Sun, 11 May 2008) | 2 lines #2709: clarification. ........ r63053 | georg.brandl | 2008-05-11 06:42:28 -0400 (Sun, 11 May 2008) | 2 lines #2659: add ``break_on_hyphens`` to TextWrapper. ........ r63057 | georg.brandl | 2008-05-11 06:59:39 -0400 (Sun, 11 May 2008) | 2 lines #2741: clarification of value range for address_family. ........ r63058 | georg.brandl | 2008-05-11 07:09:35 -0400 (Sun, 11 May 2008) | 2 lines #2452: timeout is used for all blocking operations. ........ r63059 | andrew.kuchling | 2008-05-11 09:33:56 -0400 (Sun, 11 May 2008) | 2 lines #1792: Improve performance of marshal.dumps() on large objects by increasing the size of the buffer more quickly. ........ r63060 | andrew.kuchling | 2008-05-11 10:00:00 -0400 (Sun, 11 May 2008) | 1 line #1858: re-apply patch for this, adding the missing files ........ r63061 | benjamin.peterson | 2008-05-11 10:13:25 -0400 (Sun, 11 May 2008) | 2 lines Add the "until" command to pdb ........ r63062 | georg.brandl | 2008-05-11 10:17:13 -0400 (Sun, 11 May 2008) | 2 lines Add some sentence endings. ........
2008-05-15 21:03:33 -03:00
operations (like connection attempts) will timeout after that many seconds
Merged revisions 63562,63570,63728,63734,63784,63788,63802,63817,63827,63839,63887,63975,63998 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r63562 | martin.v.loewis | 2008-05-23 17:06:50 +0200 (Fri, 23 May 2008) | 2 lines Patch #1722225: Support QNX 6. ........ r63570 | trent.nelson | 2008-05-23 22:33:14 +0200 (Fri, 23 May 2008) | 1 line Introduce a user macro named $(externalsDir), which should point to the root directory of where all the external sources should live. Developers can change this value if their external sources live elsewhere. The default of '..\..' matches the current status quo. ........ r63728 | gregory.p.smith | 2008-05-26 23:16:34 +0200 (Mon, 26 May 2008) | 4 lines Fix issue2589: there was a potential integer overflow leading to memory corruption on esoteric platforms and incorrect behavior on normal platforms. ........ r63734 | gregory.p.smith | 2008-05-27 00:07:28 +0200 (Tue, 27 May 2008) | 3 lines Fix issue2588: Do not execute str[size-1] = '\0' when a 0 size is passed in. (The assert won't prevent this in non-debug builds). ........ r63784 | raymond.hettinger | 2008-05-29 10:38:23 +0200 (Thu, 29 May 2008) | 1 line Fix two typos. ........ r63788 | facundo.batista | 2008-05-29 18:39:26 +0200 (Thu, 29 May 2008) | 6 lines Fixed the semantic of timeout for socket.create_connection and all the upper level libraries that use it, including urllib2. Added and fixed some tests, and changed docs correspondingly. Thanks to John J Lee for the patch and the pusing, :) ........ r63802 | mark.dickinson | 2008-05-30 04:46:53 +0200 (Fri, 30 May 2008) | 2 lines Fix typo in testSum ........ r63817 | raymond.hettinger | 2008-05-30 20:20:50 +0200 (Fri, 30 May 2008) | 8 lines * Mark intermedidate computes values (hi, lo, yr) as volatile. * Expand comments. * Swap variable names in the sum_exact code so that x and y are consistently chosen as the larger and smaller magnitude values respectively. ........ r63827 | raymond.hettinger | 2008-05-31 05:24:31 +0200 (Sat, 31 May 2008) | 1 line Implement heapq in terms of less-than (to match list.sort()). ........ r63839 | gerhard.haering | 2008-05-31 23:33:27 +0200 (Sat, 31 May 2008) | 2 lines Fixed rowcount for SELECT statements. They're -1 now (again), for better DB-API 2.0 compliance. ........ r63887 | gregory.p.smith | 2008-06-02 06:05:52 +0200 (Mon, 02 Jun 2008) | 4 lines Fix issue 2782: be less strict about the format string type in strftime. Accept unicode and anything else ParseTuple "s#" can deal with. This matches the time.strftime behavior. ........ r63975 | neal.norwitz | 2008-06-06 06:47:01 +0200 (Fri, 06 Jun 2008) | 3 lines Aldo Cortesi confirmed this is still needed for OpenBSD 4.2 and 4.3. (I didn't regen configure, since I don't have a working autoconf.) ........ r63998 | raymond.hettinger | 2008-06-06 23:47:51 +0200 (Fri, 06 Jun 2008) | 1 line Issue 3501: Make heapq support both __le__ and __lt__. ........
2008-06-10 14:40:04 -03:00
(if it is not given, the global default timeout setting is used).
2011-01-29 20:39:00 -04:00
The optional *source_address* parameter may be a tuple of a (host, port)
to use as the source address the HTTP connection is made from.
The optional *blocksize* parameter sets the buffer size in bytes for
sending a file-like message body.
2007-08-15 11:28:22 -03:00
For example, the following calls all create instances that connect to the server
at the same host and port::
>>> h1 = http.client.HTTPConnection('www.python.org')
>>> h2 = http.client.HTTPConnection('www.python.org:80')
>>> h3 = http.client.HTTPConnection('www.python.org', 80)
>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)
2007-08-15 11:28:22 -03:00
.. versionchanged:: 3.2
*source_address* was added.
2007-08-15 11:28:22 -03:00
2013-03-19 05:22:56 -03:00
.. versionchanged:: 3.4
The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
not longer supported.
.. versionchanged:: 3.7
*blocksize* parameter was added.
.. class:: HTTPSConnection(host, port=None, key_file=None, \
cert_file=None[, timeout], \
source_address=None, *, context=None, \
check_hostname=None, blocksize=8192)
2007-08-15 11:28:22 -03:00
A subclass of :class:`HTTPConnection` that uses SSL for communication with
secure servers. Default port is ``443``. If *context* is specified, it
must be a :class:`ssl.SSLContext` instance describing the various SSL
options.
Please read :ref:`ssl-security` for more information on best practices.
.. versionchanged:: 3.2
*source_address*, *context* and *check_hostname* were added.
.. versionchanged:: 3.2
This class now supports HTTPS virtual hosts if possible (that is,
if :data:`ssl.HAS_SNI` is true).
2013-03-19 05:22:56 -03:00
.. versionchanged:: 3.4
The *strict* parameter was removed. HTTP 0.9-style "Simple Responses" are
no longer supported.
.. versionchanged:: 3.4.3
This class now performs all the necessary certificate and hostname checks
by default. To revert to the previous, unverified, behavior
:func:`ssl._create_unverified_context` can be passed to the *context*
parameter.
.. versionchanged:: 3.8
This class now enables TLS 1.3
:attr:`ssl.SSLContext.post_handshake_auth` for the default *context* or
when *cert_file* is passed with a custom *context*.
.. deprecated:: 3.6
*key_file* and *cert_file* are deprecated in favor of *context*.
Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
:func:`ssl.create_default_context` select the system's trusted CA
certificates for you.
The *check_hostname* parameter is also deprecated; the
:attr:`ssl.SSLContext.check_hostname` attribute of *context* should
be used instead.
2007-08-15 11:28:22 -03:00
.. class:: HTTPResponse(sock, debuglevel=0, method=None, url=None)
2007-08-15 11:28:22 -03:00
Class whose instances are returned upon successful connection. Not
instantiated directly by user.
2007-08-15 11:28:22 -03:00
2013-03-19 05:22:56 -03:00
.. versionchanged:: 3.4
The *strict* parameter was removed. HTTP 0.9 style "Simple Responses" are
no longer supported.
This module provides the following function:
.. function:: parse_headers(fp)
Parse the headers from a file pointer *fp* representing a HTTP
request/response. The file has to be a :class:`BufferedIOBase` reader
(i.e. not text) and must provide a valid :rfc:`2822` style header.
This function returns an instance of :class:`http.client.HTTPMessage`
that holds the header fields, but no payload
(the same as :attr:`HTTPResponse.msg`
and :attr:`http.server.BaseHTTPRequestHandler.headers`).
After returning, the file pointer *fp* is ready to read the HTTP body.
.. note::
:meth:`parse_headers` does not parse the start-line of a HTTP message;
it only parses the ``Name: value`` lines. The file has to be ready to
read these field lines, so the first line should already be consumed
before calling the function.
2007-08-15 11:28:22 -03:00
The following exceptions are raised as appropriate:
.. exception:: HTTPException
The base class of the other exceptions in this module. It is a subclass of
:exc:`Exception`.
.. exception:: NotConnected
A subclass of :exc:`HTTPException`.
.. exception:: InvalidURL
A subclass of :exc:`HTTPException`, raised if a port is given and is either
non-numeric or empty.
.. exception:: UnknownProtocol
A subclass of :exc:`HTTPException`.
.. exception:: UnknownTransferEncoding
A subclass of :exc:`HTTPException`.
.. exception:: UnimplementedFileMode
A subclass of :exc:`HTTPException`.
.. exception:: IncompleteRead
A subclass of :exc:`HTTPException`.
.. exception:: ImproperConnectionState
A subclass of :exc:`HTTPException`.
.. exception:: CannotSendRequest
A subclass of :exc:`ImproperConnectionState`.
.. exception:: CannotSendHeader
A subclass of :exc:`ImproperConnectionState`.
.. exception:: ResponseNotReady
A subclass of :exc:`ImproperConnectionState`.
.. exception:: BadStatusLine
A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP
status code that we don't understand.
.. exception:: LineTooLong
A subclass of :exc:`HTTPException`. Raised if an excessively long line
is received in the HTTP protocol from the server.
.. exception:: RemoteDisconnected
A subclass of :exc:`ConnectionResetError` and :exc:`BadStatusLine`. Raised
by :meth:`HTTPConnection.getresponse` when the attempt to read the response
results in no data read from the connection, indicating that the remote end
has closed the connection.
.. versionadded:: 3.5
Previously, :exc:`BadStatusLine`\ ``('')`` was raised.
The constants defined in this module are:
2007-08-15 11:28:22 -03:00
.. data:: HTTP_PORT
The default port for the HTTP protocol (always ``80``).
.. data:: HTTPS_PORT
The default port for the HTTPS protocol (always ``443``).
.. data:: responses
This dictionary maps the HTTP 1.1 status codes to the W3C names.
2008-05-26 13:32:26 -03:00
Example: ``http.client.responses[http.client.NOT_FOUND]`` is ``'Not Found'``.
2007-08-15 11:28:22 -03:00
See :ref:`http-status-codes` for a list of HTTP status codes that are
available in this module as constants.
2007-08-15 11:28:22 -03:00
.. _httpconnection-objects:
HTTPConnection Objects
----------------------
:class:`HTTPConnection` instances have the following methods:
.. method:: HTTPConnection.request(method, url, body=None, headers={}, *, \
encode_chunked=False)
2007-08-15 11:28:22 -03:00
This will send a request to the server using the HTTP request
method *method* and the selector *url*.
If *body* is specified, the specified data is sent after the headers are
finished. It may be a :class:`str`, a :term:`bytes-like object`, an
open :term:`file object`, or an iterable of :class:`bytes`. If *body*
is a string, it is encoded as ISO-8859-1, the default for HTTP. If it
is a bytes-like object, the bytes are sent as is. If it is a :term:`file
object`, the contents of the file is sent; this file object should
support at least the ``read()`` method. If the file object is an
instance of :class:`io.TextIOBase`, the data returned by the ``read()``
method will be encoded as ISO-8859-1, otherwise the data returned by
``read()`` is sent as is. If *body* is an iterable, the elements of the
iterable are sent as is until the iterable is exhausted.
The *headers* argument should be a mapping of extra HTTP headers to send
with the request.
If *headers* contains neither Content-Length nor Transfer-Encoding,
but there is a request body, one of those
header fields will be added automatically. If
*body* is ``None``, the Content-Length header is set to ``0`` for
methods that expect a body (``PUT``, ``POST``, and ``PATCH``). If
*body* is a string or a bytes-like object that is not also a
:term:`file <file object>`, the Content-Length header is
set to its length. Any other type of *body* (files
and iterables in general) will be chunk-encoded, and the
Transfer-Encoding header will automatically be set instead of
Content-Length.
The *encode_chunked* argument is only relevant if Transfer-Encoding is
specified in *headers*. If *encode_chunked* is ``False``, the
HTTPConnection object assumes that all encoding is handled by the
calling code. If it is ``True``, the body will be chunk-encoded.
.. note::
Chunked transfer encoding has been added to the HTTP protocol
version 1.1. Unless the HTTP server is known to handle HTTP 1.1,
the caller must either specify the Content-Length, or must pass a
:class:`str` or bytes-like object that is not also a file as the
body representation.
.. versionadded:: 3.2
*body* can now be an iterable.
.. versionchanged:: 3.6
If neither Content-Length nor Transfer-Encoding are set in
*headers*, file and iterable *body* objects are now chunk-encoded.
The *encode_chunked* argument was added.
No attempt is made to determine the Content-Length for file
objects.
2007-08-15 11:28:22 -03:00
.. method:: HTTPConnection.getresponse()
Should be called after a request is sent to get the response from the server.
Returns an :class:`HTTPResponse` instance.
.. note::
Note that you must have read the whole response before you can send a new
request to the server.
.. versionchanged:: 3.5
If a :exc:`ConnectionError` or subclass is raised, the
:class:`HTTPConnection` object will be ready to reconnect when
a new request is sent.
2007-08-15 11:28:22 -03:00
.. method:: HTTPConnection.set_debuglevel(level)
Set the debugging level. The default debug level is ``0``, meaning no
debugging output is printed. Any value greater than ``0`` will cause all
currently defined debug output to be printed to stdout. The ``debuglevel``
is passed to any new :class:`HTTPResponse` objects that are created.
2007-08-15 11:28:22 -03:00
2009-10-01 17:20:09 -03:00
.. versionadded:: 3.1
Merged revisions 72506,72525-72526,72551,72558,72616,72654-72655,72689,72745,72750,72802,72812,72822,72824,72826-72827,72833,72876,72890,72923,72946,73026,73042,73045,73047,73065,73068-73069 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r72506 | vinay.sajip | 2009-05-09 07:07:17 -0500 (Sat, 09 May 2009) | 1 line Issue #5971: StreamHandler.handleError now swallows IOErrors which occur when trying to print a traceback. ........ r72525 | benjamin.peterson | 2009-05-09 20:38:02 -0500 (Sat, 09 May 2009) | 1 line close file explicitly ........ r72526 | benjamin.peterson | 2009-05-09 21:29:00 -0500 (Sat, 09 May 2009) | 1 line make sure files are closed using the with statement ........ r72551 | benjamin.peterson | 2009-05-10 09:16:47 -0500 (Sun, 10 May 2009) | 1 line use isinstance ........ r72558 | benjamin.peterson | 2009-05-10 18:52:09 -0500 (Sun, 10 May 2009) | 1 line sys.setdefaultencoding() strikes me as a bad example ........ r72616 | benjamin.peterson | 2009-05-13 19:33:10 -0500 (Wed, 13 May 2009) | 1 line importlib.import_module is better these days ........ r72654 | benjamin.peterson | 2009-05-14 17:37:49 -0500 (Thu, 14 May 2009) | 1 line prevent refleaks from threads ........ r72655 | benjamin.peterson | 2009-05-14 17:40:34 -0500 (Thu, 14 May 2009) | 1 line a useful decorator for cleaning up threads ........ r72689 | benjamin.peterson | 2009-05-16 13:44:34 -0500 (Sat, 16 May 2009) | 1 line use skipTest() ........ r72745 | benjamin.peterson | 2009-05-17 09:16:29 -0500 (Sun, 17 May 2009) | 1 line ignore .rst files in sphinx its self ........ r72750 | benjamin.peterson | 2009-05-17 11:59:27 -0500 (Sun, 17 May 2009) | 1 line chop off slash ........ r72802 | georg.brandl | 2009-05-20 13:35:27 -0500 (Wed, 20 May 2009) | 1 line #6051: refer to email examples for better way to construct email messages. ........ r72812 | michael.foord | 2009-05-21 17:57:02 -0500 (Thu, 21 May 2009) | 1 line Rename TestCase._result to _resultForDoCleanups to avoid potential clashes in TestCase subclasses. Issue 6072. ........ r72822 | georg.brandl | 2009-05-22 04:33:25 -0500 (Fri, 22 May 2009) | 1 line #6084: fix example. ........ r72824 | georg.brandl | 2009-05-22 04:43:17 -0500 (Fri, 22 May 2009) | 1 line Fix references to file-related functions and methods (os.* vs file.*). ........ r72826 | georg.brandl | 2009-05-22 04:49:42 -0500 (Fri, 22 May 2009) | 1 line Fix confusing wording. ........ r72827 | georg.brandl | 2009-05-22 04:50:30 -0500 (Fri, 22 May 2009) | 1 line s/use/call/ ........ r72833 | georg.brandl | 2009-05-22 12:00:17 -0500 (Fri, 22 May 2009) | 1 line #6078: _warnings is a builtin module and has no standard init_warnings function. ........ r72876 | benjamin.peterson | 2009-05-23 15:59:09 -0500 (Sat, 23 May 2009) | 1 line remove mention of old ctypes version ........ r72890 | gregory.p.smith | 2009-05-24 13:00:13 -0500 (Sun, 24 May 2009) | 2 lines add a versionadded tag for set_tunnel ........ r72923 | michael.foord | 2009-05-25 15:36:56 -0500 (Mon, 25 May 2009) | 1 line Make assertSequenceEqual error messages less cryptic, particularly for nested sequences. ........ r72946 | ronald.oussoren | 2009-05-26 13:44:48 -0500 (Tue, 26 May 2009) | 2 lines Fixes issue 6110 ........ r73026 | r.david.murray | 2009-05-29 14:30:27 -0500 (Fri, 29 May 2009) | 3 lines Issue 6141: document that the first item of args is still the command name even when executable is specified. ........ r73042 | benjamin.peterson | 2009-05-29 22:10:52 -0500 (Fri, 29 May 2009) | 1 line no fdatasync on macos ........ r73045 | georg.brandl | 2009-05-30 02:26:04 -0500 (Sat, 30 May 2009) | 1 line #6146: fix markup bug. ........ r73047 | georg.brandl | 2009-05-30 05:33:23 -0500 (Sat, 30 May 2009) | 1 line Fix some more small markup problems. ........ r73065 | antoine.pitrou | 2009-05-30 16:39:25 -0500 (Sat, 30 May 2009) | 3 lines The test for #5330 wasn't correct. ........ r73068 | antoine.pitrou | 2009-05-30 16:45:40 -0500 (Sat, 30 May 2009) | 3 lines Update ACKS ........ r73069 | benjamin.peterson | 2009-05-30 19:42:42 -0500 (Sat, 30 May 2009) | 1 line fix signature ........
2009-06-01 19:42:33 -03:00
.. method:: HTTPConnection.set_tunnel(host, port=None, headers=None)
Set the host and the port for HTTP Connect Tunnelling. This allows running
the connection through a proxy server.
The host and port arguments specify the endpoint of the tunneled connection
(i.e. the address included in the CONNECT request, *not* the address of the
proxy server).
The headers argument should be a mapping of extra HTTP headers to send with
the CONNECT request.
For example, to tunnel through a HTTPS proxy server running locally on port
8080, we would pass the address of the proxy to the :class:`HTTPSConnection`
constructor, and the address of the host that we eventually want to reach to
the :meth:`~HTTPConnection.set_tunnel` method::
>>> import http.client
>>> conn = http.client.HTTPSConnection("localhost", 8080)
>>> conn.set_tunnel("www.python.org")
>>> conn.request("HEAD","/index.html")
2009-07-25 01:27:38 -03:00
.. versionadded:: 3.2
2007-08-15 11:28:22 -03:00
2007-08-15 11:28:22 -03:00
.. method:: HTTPConnection.connect()
Connect to the server specified when the object was created. By default,
this is called automatically when making a request if the client does not
already have a connection.
2007-08-15 11:28:22 -03:00
.. method:: HTTPConnection.close()
Close the connection to the server.
.. attribute:: HTTPConnection.blocksize
Buffer size in bytes for sending a file-like message body.
.. versionadded:: 3.7
2007-08-15 11:28:22 -03:00
As an alternative to using the :meth:`request` method described above, you can
also send your request step by step, by using the four functions below.
.. method:: HTTPConnection.putrequest(method, url, skip_host=False, \
skip_accept_encoding=False)
2007-08-15 11:28:22 -03:00
This should be the first call after the connection to the server has been
made. It sends a line to the server consisting of the *method* string,
the *url* string, and the HTTP version (``HTTP/1.1``). To disable automatic
sending of ``Host:`` or ``Accept-Encoding:`` headers (for example to accept
additional content encodings), specify *skip_host* or *skip_accept_encoding*
with non-False values.
2007-08-15 11:28:22 -03:00
.. method:: HTTPConnection.putheader(header, argument[, ...])
Send an :rfc:`822`\ -style header to the server. It sends a line to the server
consisting of the header, a colon and a space, and the first argument. If more
arguments are given, continuation lines are sent, each consisting of a tab and
an argument.
.. method:: HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)
2007-08-15 11:28:22 -03:00
Send a blank line to the server, signalling the end of the headers. The
optional *message_body* argument can be used to pass a message body
associated with the request.
If *encode_chunked* is ``True``, the result of each iteration of
*message_body* will be chunk-encoded as specified in :rfc:`7230`,
Section 3.3.1. How the data is encoded is dependent on the type of
*message_body*. If *message_body* implements the :ref:`buffer interface
<bufferobjects>` the encoding will result in a single chunk.
If *message_body* is a :class:`collections.abc.Iterable`, each iteration
of *message_body* will result in a chunk. If *message_body* is a
:term:`file object`, each call to ``.read()`` will result in a chunk.
The method automatically signals the end of the chunk-encoded data
immediately after *message_body*.
.. note:: Due to the chunked encoding specification, empty chunks
yielded by an iterator body will be ignored by the chunk-encoder.
This is to avoid premature termination of the read of the request by
the target server due to malformed encoding.
.. versionadded:: 3.6
Chunked encoding support. The *encode_chunked* parameter was
added.
2007-08-15 11:28:22 -03:00
.. method:: HTTPConnection.send(data)
Send data to the server. This should be used directly only after the
:meth:`endheaders` method has been called and before :meth:`getresponse` is
called.
.. _httpresponse-objects:
HTTPResponse Objects
--------------------
An :class:`HTTPResponse` instance wraps the HTTP response from the
server. It provides access to the request headers and the entity
body. The response is an iterable object and can be used in a with
statement.
2007-08-15 11:28:22 -03:00
.. versionchanged:: 3.5
The :class:`io.BufferedIOBase` interface is now implemented and
all of its reader operations are supported.
2007-08-15 11:28:22 -03:00
.. method:: HTTPResponse.read([amt])
Reads and returns the response body, or up to the next *amt* bytes.
.. method:: HTTPResponse.readinto(b)
Reads up to the next len(b) bytes of the response body into the buffer *b*.
Returns the number of bytes read.
.. versionadded:: 3.3
2007-08-15 11:28:22 -03:00
.. method:: HTTPResponse.getheader(name, default=None)
2007-08-15 11:28:22 -03:00
Return the value of the header *name*, or *default* if there is no header
matching *name*. If there is more than one header with the name *name*,
return all of the values joined by ', '. If 'default' is any iterable other
than a single string, its elements are similarly returned joined by commas.
2007-08-15 11:28:22 -03:00
.. method:: HTTPResponse.getheaders()
Return a list of (header, value) tuples.
2010-09-20 22:57:43 -03:00
.. method:: HTTPResponse.fileno()
Return the ``fileno`` of the underlying socket.
2007-08-15 11:28:22 -03:00
.. attribute:: HTTPResponse.msg
A :class:`http.client.HTTPMessage` instance containing the response
headers. :class:`http.client.HTTPMessage` is a subclass of
:class:`email.message.Message`.
2007-08-15 11:28:22 -03:00
.. attribute:: HTTPResponse.version
HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.
.. attribute:: HTTPResponse.url
URL of the resource retrieved, commonly used to determine if a redirect was followed.
.. attribute:: HTTPResponse.headers
Headers of the response in the form of an :class:`email.message.EmailMessage` instance.
2007-08-15 11:28:22 -03:00
.. attribute:: HTTPResponse.status
Status code returned by server.
.. attribute:: HTTPResponse.reason
Reason phrase returned by server.
.. attribute:: HTTPResponse.debuglevel
A debugging hook. If :attr:`debuglevel` is greater than zero, messages
will be printed to stdout as the response is read and parsed.
.. attribute:: HTTPResponse.closed
Is ``True`` if the stream is closed.
.. method:: HTTPResponse.geturl()
.. deprecated:: 3.9
Deprecated in favor of :attr:`~HTTPResponse.url`.
.. method:: HTTPResponse.info()
.. deprecated:: 3.9
Deprecated in favor of :attr:`~HTTPResponse.headers`.
.. method:: HTTPResponse.getstatus()
.. deprecated:: 3.9
Deprecated in favor of :attr:`~HTTPResponse.status`.
2007-08-15 11:28:22 -03:00
Examples
--------
Here is an example session that uses the ``GET`` method::
2008-05-26 13:32:26 -03:00
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
2007-08-15 11:28:22 -03:00
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
2007-08-15 11:28:22 -03:00
200 OK
>>> data1 = r1.read() # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while chunk := r1.read(200):
... print(repr(chunk))
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn = http.client.HTTPSConnection("docs.python.org")
2007-08-15 11:28:22 -03:00
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
2007-08-15 11:28:22 -03:00
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
Here is an example session that uses the ``HEAD`` method. Note that the
``HEAD`` method never returns any data. ::
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("HEAD", "/")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b''
True
2007-08-15 11:28:22 -03:00
Here is an example session that shows how to ``POST`` requests::
>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
2007-08-15 11:28:22 -03:00
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = http.client.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
2007-08-15 11:28:22 -03:00
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
302 Found
2007-08-15 11:28:22 -03:00
>>> data = response.read()
>>> data
b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
2007-08-15 11:28:22 -03:00
>>> conn.close()
Client side ``HTTP PUT`` requests are very similar to ``POST`` requests. The
difference lies only the server side where HTTP server will allow resources to
2013-03-13 17:42:47 -03:00
be created via ``PUT`` request. It should be noted that custom HTTP methods
+are also handled in :class:`urllib.request.Request` by sending the appropriate
+method attribute.Here is an example session that shows how to do ``PUT``
request using http.client::
>>> # This creates an HTTP message
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK
.. _httpmessage-objects:
HTTPMessage Objects
-------------------
2009-04-01 21:24:00 -03:00
An :class:`http.client.HTTPMessage` instance holds the headers from an HTTP
response. It is implemented using the :class:`email.message.Message` class.
2009-04-01 21:24:00 -03:00
.. XXX Define the methods that clients can depend upon between versions.