Home > Backend Development > Python Tutorial > In-depth understanding of the http.client module in Python3

In-depth understanding of the http.client module in Python3

高洛峰
Release: 2017-03-31 09:42:28
Original
7332 people have browsed it

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.

  • ##http.client is a low-level HTTP protocol client, which is used by higher-level ones. Used by the urllib.request module.

  • ##http.server Contains classes for basic HTTP servers based on socketserver
  • ##http.cookies implements cookies #. ##State
  • Management
  • http.cookiejar Related to cookies

  • ##http module also defines a series of HTTP

    states Code

    .
HTTPStatus class is

##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_PORT

The 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.responses

Dictionary 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>, ...]
Copy after login

Basic class

##HTTPConnection class

HTTPConnection The instance represents a transaction with the HTTP server.

A host and optional port number should be passed when instantiating HTTPConnection. If no port is passed and the host

string

is 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)
Copy after login
source_address was added in version 3.2.

The strict parameter was removed in version 3.4.

HTTPSConnection Class

>>> 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)
Copy after login

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)
Copy after login

This instance will be returned once the connection is successful. Objects of this class cannot be instantiated directly by the user.

HTTPMessage class

HTTPMessage instance holds the headers returned from the HTTP response.

Exception Class

HTTP

Exception

Class

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

  • ##IncompletedRead

  • ImproperConnectionState

  • BadStatusLine

  • LineTooLong

  • ##CannotSendRequest
  • CannotSendHeader
  • ResponseNotReady
  • RemoteDisconnected
  • ##Class method

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 the

debugging

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 read

3. 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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template