案例一:
代码语言:javascript复制class RunMain():
def send_post(self, url, data): # 定义一个方法,传入需要的参数url和data
# 参数必须按照url、data顺序传入
result = requests.post(url=url, data=data).json() # 因为这里要封装post方法,所以这里的url和data值不能写死
res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)
return res
def send_get(self, url, data):
result = requests.get(url=url, data=data)
res = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2)
return res
def run_main(self, method, url=None, data=None): # 定义一个run_main函数,通过传过来的method来进行不同的get或post请求
result = None
if method == 'post':
result = self.send_post(url, data)
elif method == 'get':
result = self.send_get(url, data)
else:
print("method值错误!!!")
return result
if __name__ == '__main__': # 通过写死参数,来验证我们写的请求是否正确
result = RunMain().run_main('post', 'http://127.0.0.1:8888/login', 'name=xiaoming&pwd=')
print(result)
案例二:
代码语言:javascript复制import requests,urllib3
from common.readFile import ReadFile
class Request(object):
"""
请求类
"""
urllib3.disable_warnings()
def __init__(self):
pass
def request(self, method, url, param, headers):
"""
请求方法
:param method:
:param url:
:param param:
:param headers:
:return:
"""
try:
if method == 'get' or method == 'GET' or method == 'Get':
r = requests.get(url = url, headers=headers, json = param, verify=False)
return r.json()
elif method == 'post' or method == 'POST' or method == 'Post':
r = requests.post(url = url, headers = headers, json = param, verify=False)
return r.json()
else:
return "请求方式请传GET或POST"
except Exception as e:
return "request报错:{0}".format(e)
if __name__=='__main__':
test = Request()
test.request()