码迷,mamicode.com
首页 > 编程语言 > 详细

Python--Get and Post

时间:2017-09-05 15:56:19      阅读:242      评论:0      收藏:0      [点我收藏+]

标签: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‘


Python--Get and Post

标签:code   ==   parse   pre   response   post   res   def   return   

原文地址:http://www.cnblogs.com/fqfanqi/p/7478556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!