本例中所用数据封装格式为{“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中文参数传递出错的一种解决办法:
详见http://blog.csdn.net/y396397735/article/details/47421719