整理Python官网给的sample:https://docs.python.org/3/library/http.client.html

Python作为客户端(client)对服务器(server)进行request操作,并从服务器中得到response。

protocal有HTTPS和HTTP,method有GET和POST。

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
import http.client
import urllib.parse


def do_get(protocol, host, url):
if protocol == "HTTPS":
conn = http.client.HTTPSConnection(host)
else:
conn = http.client.HTTPConnection(host)
conn.request("GET", url)
return conn


def do_post(protocol, host, url, params):
if protocol == "HTTPS":
conn = http.client.HTTPSConnection(host)
else:
conn = http.client.HTTPConnection(host)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
conn.request("POST", url, params, headers)
return conn


def request(method, protocol, host, url, params):
conn = None
try:
if method == "GET":
conn = do_get(protocol, host, url)
elif method == "POST":
conn = do_post(protocol, host, url, params)
if conn is not None:
response = conn.getresponse()
if response.status // 100 > 3:
return '{} {}'.format(response.status, response.reason)
result = response.read() # read entire content.
conn.close()
return result
except Exception as e:
return e
return None


print(request("GET", "HTTPS", "docs.python.org",
"/3/_sources/library/http.client.txt", ""))

params = urllib.parse.urlencode({
'@number': 12524,
'@type': 'issue',
'@action': 'show'
})
print(request("POST", "HTTP", "bugs.python.org", "", params))