http.client --- HTTP 協定用戶端¶
This module defines classes that implement the client side of the HTTP and
HTTPS protocols. It is normally not used directly --- the module
urllib.request uses it to handle URLs that use HTTP and HTTPS.
也參考
The Requests package is recommended for a higher-level HTTP client interface.
備註
HTTPS support is only available if Python was compiled with SSL support
(through the ssl module).
可用性: not WASI.
此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台。
The module provides the following classes:
- class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192)¶
An
HTTPConnectioninstance 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 formhost:port, else the default HTTP port (80) is used. If the optional timeout 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 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.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)
在 3.2 版的變更: 新增 source_address。
在 3.4 版的變更: The strict parameter was removed. HTTP 0.9-style "Simple Responses" are no longer supported.
在 3.7 版的變更: 新增 blocksize 參數。
- class http.client.HTTPSConnection(host, port=None, *, [timeout, ]source_address=None, context=None, blocksize=8192)¶
A subclass of
HTTPConnectionthat uses SSL for communication with secure servers. Default port is443. If context is specified, it must be assl.SSLContextinstance describing the various SSL options.Please read Security considerations for more information on best practices.
在 3.2 版的變更: 新增 source_address、context 與 check_hostname。
在 3.2 版的變更: This class now supports HTTPS virtual hosts if possible (that is, if
ssl.HAS_SNIis true).在 3.4 版的變更: The strict parameter was removed. HTTP 0.9-style "Simple Responses" are no longer supported.
在 3.4.3 版的變更: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior
ssl._create_unverified_context()can be passed to the context parameter.在 3.8 版的變更: This class now enables TLS 1.3
ssl.SSLContext.post_handshake_authfor the default context or when cert_file is passed with a custom context.在 3.10 版的變更: This class now sends an ALPN extension with protocol indicator
http/1.1when no context is given. Custom context should set ALPN protocols withset_alpn_protocols().在 3.12 版的變更: The deprecated key_file, cert_file and check_hostname parameters have been removed.
- class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)¶
Class whose instances are returned upon successful connection. Not instantiated directly by user.
在 3.4 版的變更: The strict parameter was removed. HTTP 0.9 style "Simple Responses" are no longer supported.
This module provides the following function:
- http.client.parse_headers(fp)¶
Parse the headers from a file pointer fp representing a HTTP request/response. The file has to be a
BufferedIOBasereader (i.e. not text) and must provide a valid RFC 5322 style header.This function returns an instance of
http.client.HTTPMessagethat holds the header fields, but no payload (the same asHTTPResponse.msgandhttp.server.BaseHTTPRequestHandler.headers). After returning, the file pointer fp is ready to read the HTTP body.備註
parse_headers()does not parse the start-line of a HTTP message; it only parses theName: valuelines. The file has to be ready to read these field lines, so the first line should already be consumed before calling the function.
The following exceptions are raised as appropriate:
- exception http.client.HTTPException¶
The base class of the other exceptions in this module. It is a subclass of
Exception.
- exception http.client.NotConnected¶
HTTPException的子類別。
- exception http.client.InvalidURL¶
A subclass of
HTTPException, raised if a port is given and is either non-numeric or empty.
- exception http.client.UnknownProtocol¶
HTTPException的子類別。
- exception http.client.UnknownTransferEncoding¶
HTTPException的子類別。
- exception http.client.UnimplementedFileMode¶
HTTPException的子類別。
- exception http.client.IncompleteRead¶
HTTPException的子類別。
- exception http.client.ImproperConnectionState¶
HTTPException的子類別。
- exception http.client.CannotSendRequest¶
A subclass of
ImproperConnectionState.
- exception http.client.CannotSendHeader¶
A subclass of
ImproperConnectionState.
- exception http.client.ResponseNotReady¶
A subclass of
ImproperConnectionState.
- exception http.client.BadStatusLine¶
A subclass of
HTTPException. Raised if a server responds with a HTTP status code that we don't understand.
- exception http.client.LineTooLong¶
A subclass of
HTTPException. Raised if an excessively long line is received in the HTTP protocol from the server.
- exception http.client.RemoteDisconnected¶
A subclass of
ConnectionResetErrorandBadStatusLine. Raised byHTTPConnection.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.在 3.5 版被加入: Previously,
BadStatusLine('')was raised.
The constants defined in this module are:
- http.client.HTTP_PORT¶
The default port for the HTTP protocol (always
80).
- http.client.HTTPS_PORT¶
The default port for the HTTPS protocol (always
443).
- http.client.responses¶
This dictionary maps the HTTP 1.1 status codes to the W3C names.
Example:
http.client.responses[http.client.NOT_FOUND]is'Not Found'.
See HTTP 狀態碼 for a list of HTTP status codes that are available in this module as constants.
HTTPConnection 物件¶
HTTPConnection instances have the following methods:
- HTTPConnection.request(method, url, body=None, headers={}, *, encode_chunked=False)¶
This will send a request to the server using the HTTP request method method and the request URI url. The provided url must be an absolute path to conform with RFC 2616 §5.1.2 (unless connecting to an HTTP proxy server or using the
OPTIONSorCONNECTmethods).If body is specified, the specified data is sent after the headers are finished. It may be a
str, a bytes-like object, an open file object, or an iterable ofbytes. 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 file object, the contents of the file is sent; this file object should support at least theread()method. If the file object is an instance ofio.TextIOBase, the data returned by theread()method will be encoded as ISO-8859-1, otherwise the data returned byread()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. A Host header must be provided to conform with RFC 2616 §5.1.2 (unless connecting to an HTTP proxy server or using the
OPTIONSorCONNECTmethods).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 to0for methods that expect a body (PUT,POST, andPATCH). If body is a string or a bytes-like object that is not also a file, 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 isTrue, the body will be chunk-encoded.For example, to perform a
GETrequest tohttps://docs.python.org/3/:>>> import http.client >>> host = "docs.python.org" >>> conn = http