#python3 get and post 简单封装 from urllib import request, parseimport json def RequestMethod(methodR, url, data_dict, headers_dict): if methodR == ‘GET‘: req = request.Request if data_dict: data_str = parse.urlencode(data_dict) url_str = url + ‘?‘ + data_str if headers_dict: req = request.Request(url_str,headers=headers_dict) else: req = request.Request(url_str) else: if headers_dict: req = request.Request(url, headers=headers_dict) else: req = request.Request(url) with request.urlopen(req) as response: result = json.loads(response.read()) return result elif methodR == ‘POST‘: req = request.Request data_str = parse.urlencode(data_dict).encode(‘utf-8‘) if headers_dict: req = request.Request(url, data=data_str, headers=headers_dict) else: req = request.Request(url, data=data_str) with request.urlopen(req) as response: result = json.loads(response.read()) return result else: raise ‘error‘
时间: 2024-10-07 21:10:17