您的位置:首页 > 编程语言 > Python开发

Python post请求 import urllib urllib2模块

2015-08-05 09:39 531 查看
本例中所用数据封装格式为{“json”:json数据格式},即

{"json":{"MSG":10000, "name" : "2015", "password": "123456"}}

开发环境 win7+Eclipse+Pydev,代码如下:

import urllib
import urllib2
class Interface_post():

def __init__ (self, url, values, interfaceName):
self.url = url
self.values = values
self.interfaceName = interfaceName

def _post(self):
json_val = {"json":self.values}
data = urllib.urlencode(json_val)				#对数据url编码

try:
req = urllib2.Request(self.url)       			#post请求
response = urllib2.urlopen(req, data)
re = response.read()

print "接口名字: ", self.interfaceName
print "服务器响应代号:  ", response.getcode()
print "服务器返回值为:  ",re

except URLError, e:
print e.reason
def regist():
#regist = Interface_post(url,values,interfaceName)  		#实例化对象

regist = Interface_post(

'http://10.10.10.10:8080/working/regist', #网址

{
"MSG":10000,
"name" : "2015",
"password": "123456"
},					#数据
"接口编号1,regist"			#其他参数	,用时调用 self.interfacaName

)
return regist._post()						#调用_post方法
def login():#..略
try:
print "统计数据中---\n"
regist()
login()		#调用函数发送请求,响应慢时建议对多个接口使用多线程控制
except Exception, e:
print e.reason


Python中文参数传递出错的一种解决办法:

详见/article/10908549.html



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: