This article mainly introduces about Python3 The relevant information of the http.client module is introduced in great detail. Friends who need it can refer to it. Let’s take a look at it together.
http module introduction
The http package in Python3 contains several modules for developing the HTTP protocol.
states Code
.##newly addedhttp. Client module
##http.client module defines classes that implement http and https protocol clients This module is usually not used directly, but is encapsulated with urllib. .request module to use them to handle URLs
##Constant
##Constant in the http module:
1. http.client.HTTP_PORTThe default port number of http protocol is always port 802.http.client.HTTPS_PORTThe default port number of the https protocol is always port 443
3, http.client.responsesDictionary that maps HTTP 1.1 status codes to W3C
names For example:>>> from http import HTTPStatus >>> HTTPStatus.OK<HTTPStatus.OK: 200> >>> HTTPStatus.OK == 200True >>> http.HTTPStatus.OK.value200 >>> HTTPStatus.OK.phrase'OK' >>> HTTPStatus.OK.description'Request fulfilled, document follows' >>> list(HTTPStatus)[<HTTPStatus.CONTINUE: 100>, <HTTPStatus.SWITCHING_PROTOCOLS: 101>, ...]
http.client.responses[http.client.NOT_FOUND] is 'Not Found'
A host and optional port number should be passed when instantiating HTTPConnection. If no port is passed and the host
stringis in the form host:port, the port value will be extracted, otherwise the default 8-port will be used. If the optional parameter timeout is given, the blocking operation will timeout after the given time. If not given, the default global timeout setting will be used. The optional parameter source_address should be in the form of a tuple of host and port (host,port), used as the source address of the HTTP connection.
The sample code is as follows: http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None)
The strict parameter was removed in version 3.4.
>>> 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)
HTTPSConnection is a subclass of HTTPConnection that uses SSL to contact a secure server.
The default port is port 443. If context is specified, it must be an instance of the ssl.SSLContext class to describe the different SSL options.
key_file and cert_file have been deprecated and replaced by ssl.SSLContext.load_cert_chain(). Or use ssl.create_default_context() to select a CA certificate that the system trusts.
The check_hostname parameter has also been deprecated, use the context's ssl.SSLContext.check_hostname
property.
HTTPResponse class
HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None)
This instance will be returned once the connection is successful. Objects of this class cannot be instantiated directly by the user.
HTTPMessage classHTTPMessage instance holds the headers returned from the HTTP response.
Exception ClassHTTP
ExceptionClass
A subclass of the Exception class and also the base class of other exception classes in the http module.
Other exception classes:
NotConnected
InvalidURL
UnknownProtocol
UnknownTransferEncoding
UnimplementedFileMode
HTTPConnection object method
HTTPConnection instance has the following methods:
1. HTTPConnection.request(method, url, body=None, headers={})Use the specified method and url link to send a request to the server. If the body part is specified, the body part will be sent after the header part is sent. The body part can be a string, a bytes object, a file object, or an iterator of bytes objects. Different body types correspond to different requirements. The header parameter should be a mapping of HTTP headers, which is a dictionary type. If the header does not contain the Content-Length item, it will be automatically added based on the body. 2. HTTPConnection.getresponse() must be called after the request is sent to get the content returned by the server. What is returned is an HTTPResponse instance. 3. HTTPConnection.set_debuglevel(level)Set thedebugging
level. The default debugging level is 0, which means there is no debugging output.4. HTTPConnection.set_tunnel(host, port=None, headers=None)
Set the host and port of the HTTP tunnel link, which allows the connection to use a proxy server. 5. HTTPConnection.connect()Connect to the specified server. By default, this method is automatically called on request if the client is not connected. 6. HTTPConnection.close()Close the link. 7. HTTPConnection.putrequest(request, selector, skip_host=False, skip_accept_encoding=False)When the connection with the server is successful, this method should be called first. The content sent to the server includes: request string, selector string and HTTP protocol version. 8. HTTPConnection.putheader(header, argument[, …])Send HTTP header to the server. The content sent to the server includes: header header, colon, space and the first one in the parameter list. 9. HTTPConnection.endheaders(message_body=None)Send a blank line to the server to identify the end of the header. 10. HTTPConnection.send(data)Send data to the server. Should be called after the endheaders() method and before the getresponse() method.HTTPResponse Object Methods
HTTPResponse instances contain the HTTP response returned from the server.
It provides methods to access the request header and body parts. HTTPResponse is an iterable object and can be declared using the with statement. HTTPResponse instances have the following methods: 1. HTTPResponse.read([amt])Read and return the body part of the response. 2. HTTPResponse.readinto(b)Read the specified byte length len(b) and return to the buffer byte b.Function
Returns the number of bytes read3. HTTPResponse.getheader(name,default=None)
返回指定名称 name 的 HTTP 头部值,如果没有相应匹配的 name 值,则返回默认的 None。如果有多个相匹配的,则返回所有的值,以逗号分隔。
4、HTTPResponse.getheaders()
以元组的形式返回所有的头部信息 (header,value)。
5、HTTPResponse.fileno()
6、HTTPResponse.msg
7、HTTPResponse.version。
HTTP 协议版本
8、HTTPResponse.status
HTTP 状态码
9、HTTPResponse.reason
10、HTTPResponse.debuglevel
11、HTTPResponse.closed
如果为 True ,说明连接已关闭。
示例
import http.client import urllib,parser # # 初始化一个 https 链接 conn = http.client.HTTPSConnection("www.python.org") # 指定 request 请求的方法和请求的链接地址 conn.request("GET","/doc/") # 得到返回的 http response r1 = conn.getresponse() # HTTP 状态码 print(r1.status,r1.reason) # HTTP 头部 print(r1.getheaders()) # body 部分 print(r1.read()) # 如果连接没有关闭,打印输出前 200 个字节 if not r1.closed: print(r1.read(200)) # 关闭连接后才能重新请求 conn.close() # 请求一个不存在的文件或地址 conn.request("GET","/parrot.spam") r2 = conn.getresponse() print(r2.status,r2.reason) conn.close() # 使用 HEAD 请求,但是不会返回任何数据 conn = http.client.HTTPSConnection("www.python.org") conn.request("HEAD","/") res = conn.getresponse() print(res.status,res.reason) data = res.read() print(len(data)) conn.close() # 使用 POST 请求,提交的数据放在 body 部分 params = urllib.parse.urlencode({'@number':12524,'@type':'issue','@action':'show'}) # post 请求数据,要带上 Content-type 字段,以告知消息主体以何种方式编码 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) print(response.read().decode("utf-8")) conn.close()
The above is the detailed content of In-depth understanding of the http.client module in Python3. For more information, please follow other related articles on the PHP Chinese website!