1.导入模块
import urllib.request
2. 需要请求的url和接口参数
url = " 接口请求的地址/URL
data = "接口参数"
3. 封装get请求
data = urllib.parse.urlencode(data) 首先对data进行转码,转化成str类型
new_url = url+"?"+data URL拼接
result = urllib.request.urlopen(new_url)
response = result.read() 读取响应结果
print(response.decode("utf8")) 对响应结果解码
4.封装post请求
data = urllib.parse.urlencode(data) 首先对data进行转码,转化成str类型
data = data.encode('utf-8') post请求只支持byte类型,所以要进行再次编码
new_url = urllib.request.Request(url,data) 对url和参数进行包装
response = urllib.request.urlopen(new_url)
response = result.read() 读取响应结果
print(response.decode("utf8")) 对响应结果解码
5. urlopen提供的方法
read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
info():返回HTTPMessage对象,表示远程服务器返回的头信息
getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
geturl():返回请求的url
6.将get,post请求封装成类,提高代码复用性
class Http:
def __init__(self):
pass
def Get(self,url, data):
"""
self.Get(url,data)
:param url:
:param data:
:return:
"""
data = urllib.parse.encode('utf8')
new_url = url + "?" + data
result = urllib.request.urlopen(new_url)
response = result.read()
return response.decode('utf8')
def Post(self,url,data):
"""
self.Post(url,data)
:param url:
:param data:
:return:
"""
data = urllib.parse.encode(data)
data = data.encode('utf8')
new_url = urllib.request.Request(url, data)
result = urllib.request.urlopen(new_url)
response = result.read()
return response.decode('utf8')
网友评论