python中http协议编程_python基于http协议编程:httplib,urllib和urllib2

urllib和urllib2都是接受URL请求的相关模块,但是提供了不同的功能。两个最显著的不同如下:

urllib2 can accept a Request object to set the

headers for a URL request, urllib accepts only a URL. That means, you

cannot masquerade your User Agent string etc.

urllib2可以接受一个Request

类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,你不可以伪装你的User Agent字符串等。

urllib provides the urlencode method which is used for the generation of GET query strings,

u

rllib2 doesn't have such a function. This is one of the reasons why

urllib is often used along with urllib2.

urllib提供urlencode

方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。

提示:如果你仅做HTTP相关的,看一下httplib2,比其他几个模块好用。

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现。

importhttplib

conn= httplib.HTTPConnection("google.com")

conn.request('get', '/')printconn.getresponse().read()

conn.close()

httplib.HTTPConnection ( host [ , port [ , strict [ , timeout ]]] )

HTTPConnection类的构造函数,表示一次与服务器之间的交互,即请求/响应。参数host表示服务器主机,

如:www.csdn.net;port为端口号,默认值为80; 参数strict的 默认值为false, 表示在无法解析服务器返回的状态行时(

status line) (比较典型的状态行如: HTTP/1.0 200 OK ),是否抛BadStatusLine

异常;可选参数timeout 表示超时时间。

HTTPConnection提供的方法:

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

调用request 方法会向服务器发送一次请求,method 表示请求的方法,常用有方法有get 和post ;url 表示请求的资源的url

;body 表示提交到服务器的数据,必须是字符串(如果method 是”post” ,则可以把body 理解为html

表单中的数据);headers 表示请求的http 头。

HTTPConnection.getresponse ()

获取Http 响应。返回的对象是HTTPResponse 的实例,关于HTTPResponse 在下面 会讲解。

HTTPConnection.connect ()

连接到Http 服务器。

HTTPConnection.close ()

关闭与服务器的连接。

HTTPConnection.set_debuglevel ( level )

设置高度的级别。参数level 的默认值为0 ,表示不输出任何调试信息。

httplib.HTTPResponse

HTTPResponse表示服务器对客户端请求的响应。往往通过调用HTTPConnection.getresponse()来创建,它有如下方法和属性:

HTTPResponse.read([amt])

获取响应的消息体。如果请求的是一个普通的网页,那么该方法返回的是页面的html。可选参数amt表示从响应流中读取指定字节的数据。

HTTPResponse.getheader(name[, default])

获取响应头。Name表示头域(header field)名,可选参数default在头域名不存在的情况下作为默认值返回。

HTTPResponse.getheaders()

以列表的形式返回所有的头信息。

HTTPResponse.msg

获取所有的响应头信息。

HTTPResponse.version

获取服务器所使用的http协议版本。11表示http/1.1;10表示http/1.0。

HTTPResponse.status

获取响应的状态码。如:200表示请求成功。

HTTPResponse.reason

返回服务器处理请求的结果说明。一般为”OK”

下面通过一个例子来熟悉HTTPResponse中的方法:

importhttplib

conn= httplib.HTTPConnection("www.g.com", 80, False)

conn.request('get', '/', headers = {"Host": "www.google.com","User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5","Accept": "text/plain"})

res=conn.getresponse()print 'version:', res.versionprint 'reason:', res.reasonprint 'status:', res.statusprint 'msg:', res.msgprint 'headers:', res.getheaders()#html#print '\n' + '-' * 50 + '\n'#print res.read()

conn.close()

Httplib模块中还定义了许多常量,如:

Httplib. HTTP_PORT 的值为80,表示默认的端口号为80;

Httplib.OK 的值为200,表示请求成功返回;

Httplib. NOT_FOUND 的值为404,表示请求的资源不存在;

可以通过httplib.responses 查询相关变量的含义,如:

Print httplib.responses[httplib.NOT_FOUND] #not found

更多关于httplib的信息,请参考Python手册

httplib 模块。

################################################

urllib 和urllib2实现的功能大同小异,但urllib2要比urllib功能等各方面更高一个层次。目前的HTTP访问大部分都使用urllib2.

urllib2:

req = urllib2.Request('http://pythoneye.com')

response=urllib2.urlopen(req)

the_page= response.read()

FTP同样:

req = urllib2.Request('ftp://pythoneye.com')

urlopen返回的应答对象response有两个很有用的方法info()和geturl()

geturl — 这个返回获取的真实的URL,这个很有用,因为urlopen(或者opener对象使用的)或许

会有重定向。获取的URL或许跟请求URL不同。

Data数据

有时候你希望发送一些数据到URL

post方式:

values ={'body' : 'test short talk','via':'xxxx'}

data=urllib.urlencode(values)

req= urllib2.Request(url, data)

get方式:

data['name'] = 'Somebody Here'data['location'] = 'Northampton'data['language'] = 'Python'url_values=urllib.urlencode(data)

url= 'http://pythoneye.com/example.cgi'full_url= url + '?' +url_values

data= urllib2.open(full_url)

使用Basic HTTP Authentication:

importurllib2#Create an OpenerDirector with support for Basic HTTP Authentication...

auth_handler =urllib2.HTTPBasicAuthHandler()

auth_handler.add_password(realm='PDQ Application',

uri='https://pythoneye.com/vecrty.py',

user='user',

passwd='pass')

opener=urllib2.build_opener(auth_handler)#...and install it globally so it can be used with urlopen.

urllib2.install_opener(opener)

urllib2.urlopen('http://www. pythoneye.com/app.html')

使用代理ProxyHandler:

proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})

proxy_auth_handler=urllib2.HTTPBasicAuthHandler()

proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener=build_opener(proxy_handler, proxy_auth_handler)#This time, rather than install the OpenerDirector, we use it directly:

opener.open('http://www.example.com/login.html')

URLError–HTTPError:

from urllib2 importRequest, urlopen, URLError, HTTPError

req=Request(someurl)try:

response=urlopen(req)exceptHTTPError, e:print 'Error code:', e.codeexceptURLError, e:print 'Reason:', e.reasonelse:

.............

或者:

from urllib2 importRequest, urlopen, URLError

req=Request(someurl)try:

response=urlopen(req)exceptURLError, e:if hasattr(e, 'reason'):print 'Reason:', e.reasonelif hasattr(e, 'code'):print 'Error code:', e.codeelse:

.............

通常,URLError在没有网络连接(没有路由到特定服务器),或者服务器不存在的情况下产生

异常同样会带有”reason”属性,它是一个tuple,包含了一个错误号和一个错误信息

req = urllib2.Request('http://pythoneye.com')try:

urllib2.urlopen(req)exceptURLError, e:printe.reasonprinte.codeprint e.read()

最后需要注意的就是,当处理URLError和HTTPError的时候,应先处理HTTPError,后处理URLError

Openers和Handlers:

opener使用操作器(handlers)。所有的重活都交给这些handlers来做。每一个handler知道

怎么打开url以一种独特的url协议(http,ftp等等),或者怎么处理打开url的某些方面,如,HTTP重定向,或者HTTP

cookie。

默认opener有对普通情况的操作器 (handlers)- ProxyHandler, UnknownHandler, HTTPHandler,

HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor.

再看python API:Return an OpenerDirector instance, which chains the handlers in the order given

这就更加证明了一点,那就是opener可以看成是一个容器,这个容器当中放的是控制器,默认的,容器当中有五个控制

器,程序员也可以加入自己的控制器,然后这些控制器去干活。

classHTTPHandler(AbstractHTTPHandler):defhttp_open(self, req):returnself.do_open(httplib.HTTPConnection, req)

http_request= AbstractHTTPHandler.do_request_

HTTPHandler是Openers当中的默认控制器之一,看到这个代码,证实了urllib2是借助于httplib实现的,同时也证实了Openers和Handlers的关系。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值