利用urllib2实现http post请求源码示例
生活随笔
收集整理的這篇文章主要介紹了
利用urllib2实现http post请求源码示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在python中利用urllib2或是pycurl都可以實現http POST請求功能,下面是源碼:
#!/usr/bin/env python
#encoding: utf-8
#description: demo a simple post form
#date: 2015-12-14import urllib, urllib2def 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 WSGIServerdef application(env, start_response):print envif 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請求
總結
以上是生活随笔為你收集整理的利用urllib2实现http post请求源码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ATS统计量proxy.node.cli
- 下一篇: 在CentOS 6.3 64bit上安装