Httplib模块使用

httplib是一个相对底层的http请求模块,其上有专门的包装模块,如urllib内建模块,goto等第三方模块,但是封装的越高就越不灵活,比如urllib模块里请求错误时就不会返回结果页的内容,只有头信息,对于某些需要检测错误请求返回值的场景就不适用,所以就得用这个模块了。

    (null)
      |
      | HTTPConnection()
      v
    Idle
      |
      | putrequest()
      v
    Request-started
      |
      | ( putheader() )*  endheaders()
      v
    Request-sent
      |
      | response = getresponse()
      v
    Unread-response   [Response-headers-read]
      |\____________________
      |                     |
      | response.read()     | putrequest()
      v                     v
    Idle                  Req-started-unread-response
                     ______/|
                   /        |
   response.read() |        | ( putheader() )*  endheaders()
                   v        v
       Request-started    Req-sent-unread-response
                            |
                            | response.read()
                            v
                          Request-sent

1、对象 httplib.
(1)HTTPConnection(host[, port[, strict[, timeout]]])
说明:该类用于创建一个http类型的请求链接对象
选项:
host: 请求的服务器host,不能带http://开头
port: 服务器web服务端口
strict: 是否严格检查请求的状态行,就是http1.0/1.1 协议版本的那一行,即请求的第一行,默认为False,为True时检查错误会抛异常
timeout: 单次请求的超时时间,没有时默认使用httplib模块内的全局的超时时间

返回:返回一个HTTPConnection对象
实例:
conn1 = HTTPConnection(‘www.baidu.com:80’)
conn2 = HTTPconnection(‘www.baidu.com’,80)
conn3 = HTTPConnection(‘www.baidu.com’,80,True,10)

(2)conn.request(method, url[, body[, headers]]):
说明:发送一个请求
选项:
method: 请求的方式,如’GET’,’POST’,’HEAD’,’PUT’,’DELETE’等
url: 请求的网页路径。如:’/index.html’
body: 请求是否带数据,该参数是一个字典
headers: 请求是否带头信息,该参数是一个字典,不过键的名字是指定的http头关键字
返回:无返回,其实就是相对于向服务其发送数据,但是没有最后回车
实例:
conn.request(‘GET’, ‘/’, ”, {‘user-agent’:’test’})

(3)getresponse():
说明:获取一个http响应对象
返回:HTTPResponse对象
子函数:
<1>read([amt])
说明:获得http响应的内容部分,即网页源码
选项:
amt: 读取指定长度的字符,默认为空,即读取所有内容
返回:网页内容字符串
<2>getheaders() 获得所有的响应头内容,是一个元组列表[(date,.),(content-length,.),(content-length,.),(content-type,.),(server,.)]
<3>getheader(name[,default]) 获得指定的头内容
<4>fileno() 获得底层socket文件描述符
<5>msg 所有的头信息,和getheaders方法一样,只不过这个是原始未处理的字符串
<6>status 获得返回状态码
<7>version 当次请求的http协议版本,10是http1.0, 11是http/1.1
<8>reason 当次请求获得返回说明,200是ok,404是Not Found
(4)close():
说明:关闭指定的httpconnect链接
实例:
conn.close()

#!/usr/bin/env python
#coding=utf8

import httplib

conn = httplib.HTTPConnection('localhost', 8080, timeout=30)
conn.request('GET', 'http://localhost:8080/')

#response是HTTPResponse对象
response = conn.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders()
conn.close()
import httplib, urllib

params = urllib.urlencode({'name': 'tom', 'age': 22})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}

conn = httplib.HTTPConnection("localhost", 8080, timeout=30)
conn.request("POST", "http://localhost:8080/", params, headers)
response = conn.getresponse()
response.status
response.reason
response.read(()
response.getheaders()

2、对象 httplib.HTTPSConnection
说明:该类用于创建一个https类型的请求链接

原型:
HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout]]]]])
key_file:一个包含PEM格式的私钥文件
cert_file:一个包含PEM格式的认证文件
other:其它同http参数
返回:同样返回一个HTTPSConnection对象
注意:要创建https链接,必须要保证底层的socket模块是支持ssl的编译模式,即编译时ssl选项的开关是开着的
实例:
conn3
= HTTPSConnection(‘accounts.google.com’,443,key_file,cert_file,True,10)

总体实例:

#!/usr/bin/env python    
# -*- coding: utf-8 -*-    
import httplib  
import urllib  


def sendhttp():  
    data = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})     
    headers = {"Content-type": "application/x-www-form-urlencoded",  
               "Accept": "text/plain"}  
    conn = httplib.HTTPConnection('bugs.python.org')  
    conn.request('POST', '/', data, headers)  
    httpres = conn.getresponse()  
    print httpres.status  
    print httpres.reason  
    print httpres.read()  


if __name__ == '__main__':    
    sendhttp()   

当然还有其它的一些信息,比如异常类型,比如http的code对应表及查询字典等等,可以直接参考官网httplib文档:http://docs.python.org/library/httplib.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值