python发送post请求

python发送post请求代码示例:


import sys
import httplib, urllib
import traceback

def post(params):
	'发送post请求'
	result = {'status':500, 'reason':'', 'response':'', 'headers':''}
	httpClient = None
	try:
	    data = urllib.urlencode(params['data'])
	    httpClient = httplib.HTTPConnection(params['hostname'], params['port'], timeout=30)
	    if params.has_key('header'):
		httpClient.request("POST", params['path'], data, params['header'])
	    else:
		httpClient.request("POST", params['path'], data)
	    response = httpClient.getresponse()
	    result['status'] = response.status
	    result['reason'] = response.reason
	    result['response'] = response.read()
	    result['headers'] = response.getheaders() #获取头信息
	except:
	    self.writelog("error", 'post fail! [' + params['path'] + '][' + data + ']\n' + self.get_trace())
	finally:
	    if httpClient:
		httpClient.close()
	return result

def get_trace():
	'获得异常栈内容'
	try:
	    errmsg = "Traceback (most recent call last):\n "
	    exc_type, exc_value, exc_tb = sys.exc_info()
	    for filename, linenum, funcname, source in traceback.extract_tb(exc_tb):
		errmsg += "  File \"%-23s\", line %s, in %s() \n\t  %s \n" % (filename, linenum, funcname, source)
	    errmsg += str(exc_type.__name__) + ": " + str(exc_value)
	    #traceback.print_exc()
	except:
	    errmsg = ''
	return errmsg


#测试post请求
params = {}
params['hostname'] = "test.yanjingang.com"
params['port'] = 80
params['path'] = "/api.php"
params['data'] = {'t': 25}
params['timeout'] = 30
params['header'] = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}

res = self.post(params)
print res['status']
print res['response']



执行结果:

pythonpost

发表评论

电子邮件地址不会被公开。