标签:code == parse pre response post res def return
#python3 get and post 简单封装
from urllib import request, parse
import 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‘
标签:code == parse pre response post res def return
原文地址:http://www.cnblogs.com/fqfanqi/p/7478556.html