利用urllib2实现http post请求源码示例

本文通过使用 Python 的 urllib2 库演示了如何发起 HTTP POST 请求,并介绍了如何搭建一个基于 gevent 的简易 HTTP 服务器来接收并处理这些请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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请求


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值