封装http请求工具类
1.代码一
import requests class HttpRequest: """封装http接口请求""" def http_request(self,method,url,data=None,header=None): if method.lower() == 'get': res = requests.get(url,data,headers=header) else: res = requests.post(url,data,headers=header) return res if __name__ == '__main__': """测试代码""" login_res = HttpRequest().http_request('get','http://baidu.com') print(login_res)
2.代码二
import requests class HttpRequest: """封装http接口请求""" def __init__(self,method,url,data=None,header=None): self.method = method self.url = url self.data = data self.header = header def http_request(self): if self.method.lower() == 'get': res = requests.get(self.url,self.data,headers=self.header) else: res = requests.post(self.url,self.data,headers=self.header) return res if __name__ == '__main__': """测试代码""" login_res = HttpRequest('get','http://baidu.com').http_request() print(login_res)
3.代码三
import requests class HttpRequest: """封装http接口请求""" def http_request(self,method,url,data=None,header=None): try: if method.lower() == 'get': res = requests.get(url,data,headers=header) elif method.lower() == 'post': res = requests.post(url,data,headers=header) else: print("请求方式输入错误") except Exception as e: print('请求报错了:{}'.format(e)) raise e return res if __name__ == '__main__': """测试代码""" login_res = HttpRequest().http_request('get','http://baidu.com') print(login_res)