1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
<span id="http-client-http-protocol-client"></span><h1>http.client — HTTP protocol client</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/http/client.py">Lib/http/client.py</a></p> <span class="target" id="index-0"></span> <p>This module defines classes that implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module <a class="reference internal" href="urllib.request#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code>urllib.request</code></a> uses it to handle URLs that use HTTP and HTTPS.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference external" href="https://requests.readthedocs.io/en/latest/">Requests package</a> is recommended for a higher-level HTTP client interface.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>HTTPS support is only available if Python was compiled with SSL support (through the <a class="reference internal" href="ssl#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code>ssl</code></a> module).</p> </div> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: not Emscripten, not WASI.</p> <p>This module does not work or is not available on WebAssembly platforms <code>wasm32-emscripten</code> and <code>wasm32-wasi</code>. See <a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#wasm-availability"><span class="std std-ref">WebAssembly platforms</span></a> for more information.</p> </div> <p>The module provides the following classes:</p> <dl class="py class"> <dt class="sig sig-object py" id="http.client.HTTPConnection">
<code>class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192)</code> </dt> <dd>
<p>An <a class="reference internal" href="#http.client.HTTPConnection" title="http.client.HTTPConnection"><code>HTTPConnection</code></a> instance represents one transaction with an HTTP server. It should be instantiated by 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 <code>host:port</code>, else the default HTTP port (80) is used. If the optional <em>timeout</em> parameter is given, blocking operations (like connection attempts) will timeout after that many seconds (if it is not given, the global default timeout setting is used). The optional <em>source_address</em> parameter may be a tuple of a (host, port) to use as the source address the HTTP connection is made from. The optional <em>blocksize</em> parameter sets the buffer size in bytes for sending a file-like message body.</p> <p>For example, the following calls all create instances that connect to the server at the same host and port:</p> <pre data-language="python">>>> 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)
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span><em>source_address</em> was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The <em>strict</em> parameter was removed. HTTP 0.9-style “Simple Responses” are no longer supported.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><em>blocksize</em> parameter was added.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="http.client.HTTPSConnection">
<code>class http.client.HTTPSConnection(host, port=None, *, [timeout, ]source_address=None, context=None, blocksize=8192)</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPConnection" title="http.client.HTTPConnection"><code>HTTPConnection</code></a> that uses SSL for communication with secure servers. Default port is <code>443</code>. If <em>context</em> is specified, it must be a <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>ssl.SSLContext</code></a> instance describing the various SSL options.</p> <p>Please read <a class="reference internal" href="ssl#ssl-security"><span class="std std-ref">Security considerations</span></a> for more information on best practices.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span><em>source_address</em>, <em>context</em> and <em>check_hostname</em> were added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>This class now supports HTTPS virtual hosts if possible (that is, if <a class="reference internal" href="ssl#ssl.HAS_SNI" title="ssl.HAS_SNI"><code>ssl.HAS_SNI</code></a> is true).</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The <em>strict</em> parameter was removed. HTTP 0.9-style “Simple Responses” are no longer supported.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4.3: </span>This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior <code>ssl._create_unverified_context()</code> can be passed to the <em>context</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>This class now enables TLS 1.3 <a class="reference internal" href="ssl#ssl.SSLContext.post_handshake_auth" title="ssl.SSLContext.post_handshake_auth"><code>ssl.SSLContext.post_handshake_auth</code></a> for the default <em>context</em> or when <em>cert_file</em> is passed with a custom <em>context</em>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>This class now sends an ALPN extension with protocol indicator <code>http/1.1</code> when no <em>context</em> is given. Custom <em>context</em> should set ALPN protocols with <code>set_alpn_protocol()</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The deprecated <em>key_file</em>, <em>cert_file</em> and <em>check_hostname</em> parameters have been removed.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="http.client.HTTPResponse">
<code>class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)</code> </dt> <dd>
<p>Class whose instances are returned upon successful connection. Not instantiated directly by user.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The <em>strict</em> parameter was removed. HTTP 0.9 style “Simple Responses” are no longer supported.</p> </div> </dd>
</dl> <p>This module provides the following function:</p> <dl class="py function"> <dt class="sig sig-object py" id="http.client.parse_headers">
<code>http.client.parse_headers(fp)</code> </dt> <dd>
<p>Parse the headers from a file pointer <em>fp</em> representing a HTTP request/response. The file has to be a <code>BufferedIOBase</code> reader (i.e. not text) and must provide a valid <span class="target" id="index-2"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2822.html"><strong>RFC 2822</strong></a> style header.</p> <p>This function returns an instance of <code>http.client.HTTPMessage</code> that holds the header fields, but no payload (the same as <a class="reference internal" href="#http.client.HTTPResponse.msg" title="http.client.HTTPResponse.msg"><code>HTTPResponse.msg</code></a> and <a class="reference internal" href="http.server#http.server.BaseHTTPRequestHandler.headers" title="http.server.BaseHTTPRequestHandler.headers"><code>http.server.BaseHTTPRequestHandler.headers</code></a>). After returning, the file pointer <em>fp</em> is ready to read the HTTP body.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#http.client.parse_headers" title="http.client.parse_headers"><code>parse_headers()</code></a> does not parse the start-line of a HTTP message; it only parses the <code>Name: value</code> lines. The file has to be ready to read these field lines, so the first line should already be consumed before calling the function.</p> </div> </dd>
</dl> <p>The following exceptions are raised as appropriate:</p> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.HTTPException">
<code>exception http.client.HTTPException</code> </dt> <dd>
<p>The base class of the other exceptions in this module. It is a subclass of <a class="reference internal" href="exceptions#Exception" title="Exception"><code>Exception</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.NotConnected">
<code>exception http.client.NotConnected</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.InvalidURL">
<code>exception http.client.InvalidURL</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>, raised if a port is given and is either non-numeric or empty.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.UnknownProtocol">
<code>exception http.client.UnknownProtocol</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.UnknownTransferEncoding">
<code>exception http.client.UnknownTransferEncoding</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.UnimplementedFileMode">
<code>exception http.client.UnimplementedFileMode</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.IncompleteRead">
<code>exception http.client.IncompleteRead</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.ImproperConnectionState">
<code>exception http.client.ImproperConnectionState</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.CannotSendRequest">
<code>exception http.client.CannotSendRequest</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.ImproperConnectionState" title="http.client.ImproperConnectionState"><code>ImproperConnectionState</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.CannotSendHeader">
<code>exception http.client.CannotSendHeader</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.ImproperConnectionState" title="http.client.ImproperConnectionState"><code>ImproperConnectionState</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.ResponseNotReady">
<code>exception http.client.ResponseNotReady</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.ImproperConnectionState" title="http.client.ImproperConnectionState"><code>ImproperConnectionState</code></a>.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.BadStatusLine">
<code>exception http.client.BadStatusLine</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>. Raised if a server responds with a HTTP status code that we don’t understand.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.LineTooLong">
<code>exception http.client.LineTooLong</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#http.client.HTTPException" title="http.client.HTTPException"><code>HTTPException</code></a>. Raised if an excessively long line is received in the HTTP protocol from the server.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="http.client.RemoteDisconnected">
<code>exception http.client.RemoteDisconnected</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="exceptions#ConnectionResetError" title="ConnectionResetError"><code>ConnectionResetError</code></a> and <a class="reference internal" href="#http.client.BadStatusLine" title="http.client.BadStatusLine"><code>BadStatusLine</code></a>. Raised by <a class="reference internal" href="#http.client.HTTPConnection.getresponse" title="http.client.HTTPConnection.getresponse"><code>HTTPConnection.getresponse()</code></a> when the attempt to read the response results in no data read from the connection, indicating that the remote end has closed the connection.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5: </span>Previously, <a class="reference internal" href="#http.client.BadStatusLine" title="http.client.BadStatusLine"><code>BadStatusLine</code></a><code>('')</code> was raised.</p> </div> </dd>
</dl> <p>The constants defined in this module are:</p> <dl class="py data"> <dt class="sig sig-object py" id="http.client.HTTP_PORT">
<code>http.client.HTTP_PORT</code> </dt> <dd>
<p>The default port for the HTTP protocol (always <code>80</code>).</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="http.client.HTTPS_PORT">
<code>http.client.HTTPS_PORT</code> </dt> <dd>
<p>The default port for the HTTPS protocol (always <code>443</code>).</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="http.client.responses">
<code>http.client.responses</code> </dt> <dd>
<p>This dictionary maps the HTTP 1.1 status codes to the W3C names.</p> <p>Example: <code>http.client.responses[http.client.NOT_FOUND]</code> is <code>'Not Found'</code>.</p> </dd>
</dl> <p>See <a class="reference internal" href="http#http-status-codes"><span class="std std-ref">HTTP status codes</span></a> for a list of HTTP status codes that are available in this module as constants.</p> <section id="httpconnection-objects"> <span id="id1"></span><h2>HTTPConnection Objects</h2> <p><a class="reference internal" href="#http.client.HTTPConnection" title="http.client.HTTPConnection"><code>HTTPConnection</code></a> instances have the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.request">
<code>HTTPConnection.request(method, url, body=None, headers={}, *, encode_chunked=False)</code> </dt> <dd>
<p>This will send a request to the server using the HTTP request method <em>method</em> and the request URI <em>url</em>. The provided <em>url</em> must be an absolute path to conform with <span class="target" id="index-3"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html#section-5.1.2"><strong>RFC 2616 §5.1.2</strong></a> (unless connecting to an HTTP proxy server or using the <code>OPTIONS</code> or <code>CONNECT</code> methods).</p> <p>If <em>body</em> is specified, the specified data is sent after the headers are finished. It may be a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, a <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>, an open <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>, or an iterable of <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>. If <em>body</em> 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 <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>, the contents of the file is sent; this file object should support at least the <code>read()</code> method. If the file object is an instance of <a class="reference internal" href="io#io.TextIOBase" title="io.TextIOBase"><code>io.TextIOBase</code></a>, the data returned by the <code>read()</code> method will be encoded as ISO-8859-1, otherwise the data returned by <code>read()</code> is sent as is. If <em>body</em> is an iterable, the elements of the iterable are sent as is until the iterable is exhausted.</p> <p>The <em>headers</em> argument should be a mapping of extra HTTP headers to send with the request. A <span class="target" id="index-4"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html#section-14.23"><strong>Host header</strong></a> must be provided to conform with <span class="target" id="index-5"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2616.html#section-5.1.2"><strong>RFC 2616 §5.1.2</strong></a> (unless connecting to an HTTP proxy server or using the <code>OPTIONS</code> or <code>CONNECT</code> methods).</p> <p>If <em>headers</em> contains neither Content-Length nor Transfer-Encoding, but there is a request body, one of those header fields will be added automatically. If <em>body</em> is <code>None</code>, the Content-Length header is set to <code>0</code> for methods that expect a body (<code>PUT</code>, <code>POST</code>, and <code>PATCH</code>). If <em>body</em> is a string or a bytes-like object that is not also a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file</span></a>, the Content-Length header is set to its length. Any other type of <em>body</em> (files and iterables in general) will be chunk-encoded, and the Transfer-Encoding header will automatically be set instead of Content-Length.</p> <p>The <em>encode_chunked</em> argument is only relevant if Transfer-Encoding is specified in <em>headers</em>. If <em>encode_chunked</em> is <code>False</code>, the HTTPConnection object assumes that all encoding is handled by the calling code. If it is <code>True</code>, the body will be chunk-encoded.</p> <p>For example, to perform a <code>GET</code> request to <code>https://docs.python.org/3/</code>:</p> <pre data-language="python">>>> import http.client
>>> host = "docs.python.org"
>>> conn = http.client.HTTPSConnection(host)
>>> conn.request("GET", "/3/", headers={"Host": host})
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200 OK
</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>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 <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> or bytes-like object that is not also a file as the body representation.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span><em>body</em> can now be an iterable.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>If neither Content-Length nor Transfer-Encoding are set in <em>headers</em>, file and iterable <em>body</em> objects are now chunk-encoded. The <em>encode_chunked</em> argument was added. No attempt is made to determine the Content-Length for file objects.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.getresponse">
<code>HTTPConnection.getresponse()</code> </dt> <dd>
<p>Should be called after a request is sent to get the response from the server. Returns an <a class="reference internal" href="#http.client.HTTPResponse" title="http.client.HTTPResponse"><code>HTTPResponse</code></a> instance.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Note that you must have read the whole response before you can send a new request to the server.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>If a <a class="reference internal" href="exceptions#ConnectionError" title="ConnectionError"><code>ConnectionError</code></a> or subclass is raised, the <a class="reference internal" href="#http.client.HTTPConnection" title="http.client.HTTPConnection"><code>HTTPConnection</code></a> object will be ready to reconnect when a new request is sent.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.set_debuglevel">
<code>HTTPConnection.set_debuglevel(level)</code> </dt> <dd>
<p>Set the debugging level. The default debug level is <code>0</code>, meaning no debugging output is printed. Any value greater than <code>0</code> will cause all currently defined debug output to be printed to stdout. The <code>debuglevel</code> is passed to any new <a class="reference internal" href="#http.client.HTTPResponse" title="http.client.HTTPResponse"><code>HTTPResponse</code></a> objects that are created.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.set_tunnel">
<code>HTTPConnection.set_tunnel(host, port=None, headers=None)</code> </dt> <dd>
<p>Set the host and the port for HTTP Connect Tunnelling. This allows running the connection through a proxy server.</p> <p>The <em>host</em> and <em>port</em> arguments specify the endpoint of the tunneled connection (i.e. the address included in the CONNECT request, <em>not</em> the address of the proxy server).</p> <p>The <em>headers</em> argument should be a mapping of extra HTTP headers to send with the CONNECT request.</p> <p>As HTTP/1.1 is used for HTTP CONNECT tunnelling request, <a class="reference external" href="https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.6">as per the RFC</a>, a HTTP <code>Host:</code> header must be provided, matching the authority-form of the request target provided as the destination for the CONNECT request. If a HTTP <code>Host:</code> header is not provided via the headers argument, one is generated and transmitted automatically.</p> <p>For example, to tunnel through a HTTPS proxy server running locally on port 8080, we would pass the address of the proxy to the <a class="reference internal" href="#http.client.HTTPSConnection" title="http.client.HTTPSConnection"><code>HTTPSConnection</code></a> constructor, and the address of the host that we eventually want to reach to the <a class="reference internal" href="#http.client.HTTPConnection.set_tunnel" title="http.client.HTTPConnection.set_tunnel"><code>set_tunnel()</code></a> method:</p> <pre data-language="python">>>> import http.client
>>> conn = http.client.HTTPSConnection("localhost", 8080)
>>> conn.set_tunnel("www.python.org")
>>> conn.request("HEAD","/index.html")
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>HTTP CONNECT tunnelling requests use protocol HTTP/1.1, upgraded from protocol HTTP/1.0. <code>Host:</code> HTTP headers are mandatory for HTTP/1.1, so one will be automatically generated and transmitted if not provided in the headers argument.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.get_proxy_response_headers">
<code>HTTPConnection.get_proxy_response_headers()</code> </dt> <dd>
<p>Returns a dictionary with the headers of the response received from the proxy server to the CONNECT request.</p> <p>If the CONNECT request was not sent, the method returns <code>None</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.connect">
<code>HTTPConnection.connect()</code> </dt> <dd>
<p>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.</p> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>http.client.connect</code> with arguments <code>self</code>, <code>host</code>, <code>port</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.close">
<code>HTTPConnection.close()</code> </dt> <dd>
<p>Close the connection to the server.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPConnection.blocksize">
<code>HTTPConnection.blocksize</code> </dt> <dd>
<p>Buffer size in bytes for sending a file-like message body.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <p>As an alternative to using the <code>request()</code> method described above, you can also send your request step by step, by using the four functions below.</p> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.putrequest">
<code>HTTPConnection.putrequest(method, url, skip_host=False, skip_accept_encoding=False)</code> </dt> <dd>
<p>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 <em>method</em> string, the <em>url</em> string, and the HTTP version (<code>HTTP/1.1</code>). To disable automatic sending of <code>Host:</code> or <code>Accept-Encoding:</code> headers (for example to accept additional content encodings), specify <em>skip_host</em> or <em>skip_accept_encoding</em> with non-False values.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.putheader">
<code>HTTPConnection.putheader(header, argument[, ...])</code> </dt> <dd>
<p>Send an <span class="target" id="index-6"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc822.html"><strong>RFC 822</strong></a>-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.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.endheaders">
<code>HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)</code> </dt> <dd>
<p>Send a blank line to the server, signalling the end of the headers. The optional <em>message_body</em> argument can be used to pass a message body associated with the request.</p> <p>If <em>encode_chunked</em> is <code>True</code>, the result of each iteration of <em>message_body</em> will be chunk-encoded as specified in <span class="target" id="index-7"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7230.html"><strong>RFC 7230</strong></a>, Section 3.3.1. How the data is encoded is dependent on the type of <em>message_body</em>. If <em>message_body</em> implements the <a class="reference internal" href="../c-api/buffer#bufferobjects"><span class="std std-ref">buffer interface</span></a> the encoding will result in a single chunk. If <em>message_body</em> is a <a class="reference internal" href="collections.abc#collections.abc.Iterable" title="collections.abc.Iterable"><code>collections.abc.Iterable</code></a>, each iteration of <em>message_body</em> will result in a chunk. If <em>message_body</em> is a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>, each call to <code>.read()</code> will result in a chunk. The method automatically signals the end of the chunk-encoded data immediately after <em>message_body</em>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>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.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Chunked encoding support. The <em>encode_chunked</em> parameter was added.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPConnection.send">
<code>HTTPConnection.send(data)</code> </dt> <dd>
<p>Send data to the server. This should be used directly only after the <a class="reference internal" href="#http.client.HTTPConnection.endheaders" title="http.client.HTTPConnection.endheaders"><code>endheaders()</code></a> method has been called and before <a class="reference internal" href="#http.client.HTTPConnection.getresponse" title="http.client.HTTPConnection.getresponse"><code>getresponse()</code></a> is called.</p> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>http.client.send</code> with arguments <code>self</code>, <code>data</code>.</p> </dd>
</dl> </section> <section id="httpresponse-objects"> <span id="id2"></span><h2>HTTPResponse Objects</h2> <p>An <a class="reference internal" href="#http.client.HTTPResponse" title="http.client.HTTPResponse"><code>HTTPResponse</code></a> 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.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <a class="reference internal" href="io#io.BufferedIOBase" title="io.BufferedIOBase"><code>io.BufferedIOBase</code></a> interface is now implemented and all of its reader operations are supported.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.read">
<code>HTTPResponse.read([amt])</code> </dt> <dd>
<p>Reads and returns the response body, or up to the next <em>amt</em> bytes.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.readinto">
<code>HTTPResponse.readinto(b)</code> </dt> <dd>
<p>Reads up to the next len(b) bytes of the response body into the buffer <em>b</em>. Returns the number of bytes read.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.getheader">
<code>HTTPResponse.getheader(name, default=None)</code> </dt> <dd>
<p>Return the value of the header <em>name</em>, or <em>default</em> if there is no header matching <em>name</em>. If there is more than one header with the name <em>name</em>, return all of the values joined by ‘, ‘. If <em>default</em> is any iterable other than a single string, its elements are similarly returned joined by commas.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.getheaders">
<code>HTTPResponse.getheaders()</code> </dt> <dd>
<p>Return a list of (header, value) tuples.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.fileno">
<code>HTTPResponse.fileno()</code> </dt> <dd>
<p>Return the <code>fileno</code> of the underlying socket.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.msg">
<code>HTTPResponse.msg</code> </dt> <dd>
<p>A <code>http.client.HTTPMessage</code> instance containing the response headers. <code>http.client.HTTPMessage</code> is a subclass of <a class="reference internal" href="email.compat32-message#email.message.Message" title="email.message.Message"><code>email.message.Message</code></a>.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.version">
<code>HTTPResponse.version</code> </dt> <dd>
<p>HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.url">
<code>HTTPResponse.url</code> </dt> <dd>
<p>URL of the resource retrieved, commonly used to determine if a redirect was followed.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.headers">
<code>HTTPResponse.headers</code> </dt> <dd>
<p>Headers of the response in the form of an <a class="reference internal" href="email.message#email.message.EmailMessage" title="email.message.EmailMessage"><code>email.message.EmailMessage</code></a> instance.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.status">
<code>HTTPResponse.status</code> </dt> <dd>
<p>Status code returned by server.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.reason">
<code>HTTPResponse.reason</code> </dt> <dd>
<p>Reason phrase returned by server.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.debuglevel">
<code>HTTPResponse.debuglevel</code> </dt> <dd>
<p>A debugging hook. If <a class="reference internal" href="#http.client.HTTPResponse.debuglevel" title="http.client.HTTPResponse.debuglevel"><code>debuglevel</code></a> is greater than zero, messages will be printed to stdout as the response is read and parsed.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.client.HTTPResponse.closed">
<code>HTTPResponse.closed</code> </dt> <dd>
<p>Is <code>True</code> if the stream is closed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.geturl">
<code>HTTPResponse.geturl()</code> </dt> <dd>
<div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span>Deprecated in favor of <a class="reference internal" href="#http.client.HTTPResponse.url" title="http.client.HTTPResponse.url"><code>url</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.info">
<code>HTTPResponse.info()</code> </dt> <dd>
<div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span>Deprecated in favor of <a class="reference internal" href="#http.client.HTTPResponse.headers" title="http.client.HTTPResponse.headers"><code>headers</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.client.HTTPResponse.getcode">
<code>HTTPResponse.getcode()</code> </dt> <dd>
<div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.9: </span>Deprecated in favor of <a class="reference internal" href="#http.client.HTTPResponse.status" title="http.client.HTTPResponse.status"><code>status</code></a>.</p> </div> </dd>
</dl> </section> <section id="examples"> <h2>Examples</h2> <p>Here is an example session that uses the <code>GET</code> method:</p> <pre data-language="python">>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
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")
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
</pre> <p>Here is an example session that uses the <code>HEAD</code> method. Note that the <code>HEAD</code> method never returns any data.</p> <pre data-language="python">>>> 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
</pre> <p>Here is an example session that uses the <code>POST</code> method:</p> <pre data-language="python">>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = http.client.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
302 Found
>>> data = response.read()
>>> data
b'Redirecting to <a href="https://bugs.python.org/issue12524">https://bugs.python.org/issue12524</a>'
>>> conn.close()
</pre> <p>Client side HTTP <code>PUT</code> requests are very similar to <code>POST</code> requests. The difference lies only on the server side where HTTP servers will allow resources to be created via <code>PUT</code> requests. It should be noted that custom HTTP methods are also handled in <a class="reference internal" href="urllib.request#urllib.request.Request" title="urllib.request.Request"><code>urllib.request.Request</code></a> by setting the appropriate method attribute. Here is an example session that uses the <code>PUT</code> method:</p> <pre data-language="python">>>> # This creates an HTTP request
>>> # 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
</pre> </section> <section id="httpmessage-objects"> <span id="id3"></span><h2>HTTPMessage Objects</h2> <p>An <code>http.client.HTTPMessage</code> instance holds the headers from an HTTP response. It is implemented using the <a class="reference internal" href="email.compat32-message#email.message.Message" title="email.message.Message"><code>email.message.Message</code></a> class.</p> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/http.client.html" class="_attribution-link">https://docs.python.org/3.12/library/http.client.html</a>
</p>
</div>
|