python http.クライアントはgetとpostアクセスを行う

1963 ワード

get方式:
# -*- coding: utf-8 -*-
import http.client
url = "desk.zol.com.cn"
conn = http.client.HTTPConnection(url)
conn.request("GET", "/dongman/")
r = conn.getresponse()
print(r.status, r.reason)
data1 = r.read()

post方式:
# -*- coding:utf-8 -*-

import http.client
import urllib

url = "www.XXX.com"
params = urllib.parse.urlencode(dict({'a': 1, 'b': 2}))
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'
}

httpClient = http.client.HTTPConnection(url)
httpClient.request("POST", url, params, headers)
response = httpClient.getresponse()
print(response.status+ response.reason+ response.read()+ response.getheaders())