免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1967 | 回复: 0
打印 上一主题 下一主题

The httplib module [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-09 17:49 |只看该作者 |倒序浏览

非常形象的例子,看完就可以自己写一个。今天在用wireshark的时候,看见老大操作了可以直接编辑报文数据。自己用wireshark都有一、二年的历史了,竟然都熟视无睹,鄙视自己。不过总算自己有些进步,还是比较惬意。呵呵。
This module provides an HTTP client interface.
Example: Using the httplib module # File:
httplib-example-1.py
import httplib
USER_AGENT = "httplib-example-1.py"
class Error:
    # indicates an HTTP error
    def __init__(self, url, errcode, errmsg, headers):
        self.url = url
        self.errcode = errcode
        self.errmsg = errmsg
        self.headers = headers
    def __repr__(self):
        return (
            "" %
            (self.url, self.errcode, self.errmsg)
            )
class Server:
    def __init__(self, host):
        self.host = host
    def fetch(self, path):
        http = httplib.HTTP(self.host)
        # write header
        http.putrequest("GET", path)
        http.putheader("User-Agent", USER_AGENT)
        http.putheader("Host", self.host)
        http.putheader("Accept", "*/*")
        http.endheaders()
        # get response
        errcode, errmsg, headers = http.getreply()
        if errcode != 200:
            raise Error(errcode, errmsg, headers)
        file = http.getfile()
        return file.read()
if __name__ == "__main__":
    server = Server("www.pythonware.com")
    print server.fetch("/index.htm")
Note that the HTTP client provided by this module blocks while waiting for the server to respond. For an asynchronous solution, which among other things allows you to issue multiple requests in parallel, see the examples for the
asyncore
module.
Posting data to an HTTP server
The httplib module also allows you to send other HTTP commands, such as POST.

Example: Using the httplib module to post data # File:
httplib-example-2.py
import httplib
USER_AGENT = "httplib-example-2.py"
def post(host, path, data, type=None):
    http = httplib.HTTP(host)
    # write header
    http.putrequest("PUT", path)
    http.putheader("User-Agent", USER_AGENT)
    http.putheader("Host", host)
    if type:
        http.putheader("Content-Type", type)
    http.putheader("Content-Length", str(len(data)))
    http.endheaders()
    # write body
    http.send(data)
    # get response
    errcode, errmsg, headers = http.getreply()
    if errcode != 200:
        raise Error(errcode, errmsg, headers)
    file = http.getfile()
    return file.read()
if __name__ == "__main__":
    post("www.spam.egg", "/bacon.htm", "a piece of data", "text/plain")


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/92994/showart_1856697.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP