在python中利用urllib2或是pycurl都可以实现http POST请求功能,下面是源码:
#!/usr/bin/env python
#encoding: utf-8
#description: demo a simple post form
#date: 2015-12-14
import urllib, urllib2
def post_url(url, data):
req = urllib2.Request(url)
data = urllib.urlencode(data)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
resp = opener.open(req, data)
return resp.read()
if __name__ == '__main__':
url = 'http://127.0.0.1:8000/'
payload = {'user':'mayun', 'password':'toprich123','email': 'mayun@google.com', 'submit':'登录','type':''}
print post_url(url, payload)
为了测试python中的post功能, 我们自己动手搭建一个python版本的HTTP服务器, 基于gevent中的pywsgi.py, 源码如下
#!/usr/bin/env python
#encoding: utf-8
#benchmark: ab -n 100000 -c 100 http://127.0.0.1:8080/
#note: curl -vo /dev/null 'http://127.0.0.1:8000/'
from gevent.pywsgi import WSGIServer
def application(env, start_response):
print env
if env['REQUEST_METHOD'] == 'POST':
print env['wsgi.input'].read().strip()
status = '200 OK'
headers = [('Content-Type', 'text/html')]
start_response(status, headers)
yield '<p>Hello'
yield 'World</p>'
WSGIServer(('', 8000), application).serve_forever()
现在开启HTTP服务器
python gevent_pywsgi.py
然后向该python服务器发送HTTP POST请求
python post_data.py
下面是截图
下面是客户端接收到的响应
参考文献
[1].http://finux.iteye.com/blog/786823 很好
[2].http://cn.python-requests.org/zh_CN/latest/user/quickstart.html#post 关于requests的post请求