pythonhttplib模块使用实例

httplib模块是一个底层基础模块,实现的功能比较少,正常情况下比较少用到.推荐用urllib, urllib2, httplib2.

httpconnection 对象

class httplib.httpconnection(host[, port[, strict[, timeout[, source_address]]]])

创建httpconnection对象

httpconnection.request(method, url[, body[, headers]])

发送请求

httpconnection.getresponse()

获得响应

httpresponse对象

httpresponse.read([amt])
reads and returns the response body, or up to the next amt bytes.

httpresponse.getheader(name[, default])

获得指定头信息

httpresponse.getheaders()

获得(header, value)元组的列表

httpresponse.fileno()

获得底层socket文件描述符

httpresponse.msg

获得头内容

httpresponse.version

获得头http版本

httpresponse.status

获得返回状态码

httpresponse.reason

获得返回说明

实例

代码如下:

#!/usr/bin/python
import httplib

conn = httplib.httpconnection(“www.bitscn.com”)
conn.request(“get”, “/”)
r1 = conn.getresponse()

print r1.status, r1.reason
print ‘-‘ * 40

headers = r1.getheaders()
for h in headers:
print h
print ‘-‘ * 40

print r1.msg

输出:

代码如下:

200 ok
—————————————-
(‘content-length’, ‘106883’)
(‘accept-ranges’, ‘bytes’)
(‘vary’, ‘accept-encoding, accept-encoding’)
(‘keep-alive’, ‘timeout=20’)
(‘server’, ‘ngx_openresty’)
(‘last-modified’, ‘fri, 10 apr 2015 09:30:10 gmt’)
(‘connection’, ‘keep-alive’)
(‘etag’, ‘”55279822-1a183″‘)
(‘date’, ‘fri, 10 apr 2015 09:48:15 gmt’)
(‘content-type’, ‘text/html; charset=utf-8’)
—————————————-
server: ngx_openresty
date: fri, 10 apr 2015 09:48:15 gmt
content-type: text/html; charset=utf-8
content-length: 106883
connection: keep-alive
keep-alive: timeout=20
vary: accept-encoding
last-modified: fri, 10 apr 2015 09:30:10 gmt
vary: accept-encoding
etag: “55279822-1a183”
accept-ranges: bytes

Posted in 未分类

发表评论