Python post请求 import urllib urllib2模块

来源:互联网 发布:历年网络炒作事件 编辑:程序博客网 时间:2024/05/21 20:20

本例中所用数据封装格式为{“json”:json数据格式},即

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

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

import urllibimport urllib2class 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.reasondef 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



0 0
原创粉丝点击