#python3 get and post 简单封装
1 from urllib import request, parse
2 import json
3
4
5 def RequestMethod(methodR, url, data_dict, headers_dict):
6 if methodR == 'GET':
7 req = request.Request
8 if data_dict:
9 data_str = parse.urlencode(data_dict)
10 url_str = url + '?' + data_str
11 if headers_dict:
12 req = request.Request(url_str,headers=headers_dict)
13 else:
14 req = request.Request(url_str)
15 else:
16 if headers_dict:
17 req = request.Request(url, headers=headers_dict)
18 else:
19 req = request.Request(url)
20 with request.urlopen(req) as response:
21 result = json.loads(response.read())
22 return result
23 elif methodR == 'POST':
24 req = request.Request
25 data_str = parse.urlencode(data_dict).encode('utf-8')
26 if headers_dict:
27 req = request.Request(url, data=data_str, headers=headers_dict)
28 else:
29 req = request.Request(url, data=data_str)
30 with request.urlopen(req) as response:
31 result = json.loads(response.read())
32 return result
33 else:
34 raise 'error'