#coding=utf-8
import requests
class RequestUtil:
"""
请求工具封装类
"""
def __init__(self):
pass
def request(self,url,method,params=None,contentType=None,headers=None):
try:
if method=="get":
result=requests.get(url=url,params=params,headers=headers).json()
return result
elif method=="post":
if contentType=="application/json":
result=requests.post(url=url,json=params,headers=headers).json() #Response响应结果类可以调用json()方法转成字典格式
else:
result=requests.post(url=url,data=params,headers=headers).json() #转成dict字典,后面才可以执行result["key"]
return result
else:
print("method is not alowd")
except Exception as e:
print("请求异常:{0}".format(e))
if __name__ == '__main__':
req=RequestUtil()
url="https://api.xdclass.net/pub/api/v1/web/all_category"
result=req.request(url,"get")
print(result) #结果请求成功
req=RequestUtil()
url="https://api.xdclass.net/pub/api/v1/web/web_login"
data={"phone":"13045890834","pwd":"hdc@328216"}
result=req.request(url,"post",params=data,contentType="application/x-www-form-urlencoded")
print(result) #结果请求成功
网友评论