zoukankan      html  css  js  c++  java
  • python urllib2 httplib HTTPConnection

    copy from http://hi.baidu.com/chjj910/blog/item/7db5c24fbc699d19b2de0540.html
    python基于http协议编程:httplib,urllib和urllib2(转)
    2010-11-11 20:47
    httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现。
    import httplib
    conn 
    = httplib.HTTPConnection("google.com")
    conn.request(
    'get''/')
    print conn.getresponse().read()
    conn.close()
    httplib.HTTPConnection ( host [ , port [ , strict [ , timeout ]]] )

           HTTPConnection类的构造函数,表示一次与服务器之间的交互,即请求/响应。参数host表示服务器主机,如:http://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中的方法:

    import httplib
    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.version
    print 'reason:', res.reason
    print 'status:', res.status
    print 'msg:', res.msg
    print '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:

    import urllib2
    # 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 import Request, urlopen, URLError, HTTPError
    req
    = Request(someurl)
    try:
          response
    = urlopen(req)
    except HTTPError, e:
         
    print 'Error code: ', e.code
    except URLError, e:
         
    print 'Reason: ', e.reason
    else:
           .............

    或者:

    from urllib2 import Request, urlopen, URLError
    req
    = Request(someurl)
    try:
          response
    = urlopen(req)
    except URLError, e:
         
    if hasattr(e, 'reason'):
               
    print 'Reason: ', e.reason
         
    elif hasattr(e, 'code'):
               
    print 'Error code: ', e.code
         
    else:
                .............

    通常,URLError在没有网络连接(没有路由到特定服务器),或者服务器不存在的情况下产生
    异常同样会带有”reason”属性,它是一个tuple,包含了一个错误号和一个错误信息

    req = urllib2.Request('http://pythoneye.com')
    try:
        urllib2.urlopen(req)
    except URLError, e:
       
    print e.reason
       
    print e.code
       
    print 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可以看成是一个容器,这个容器当中放的是控制器,默认的,容器当中有五个控制
    器,程序员也可以加入自己的控制器,然后这些控制器去干活。

    class HTTPHandler(AbstractHTTPHandler):
        
    def http_open(self, req):
            
    return self.do_open(httplib.HTTPConnection, req)
         http_request
    = AbstractHTTPHandler.do_request_

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

  • 相关阅读:
    分享一个Fluent风格的邮件发送封装类
    写一个ActionFilter检测WebApi接口请求和响应
    一道有趣的面试题,小鸟和火车的问题
    Centos7 查看Mysql配置文件
    Centos7 grep命令简介
    Centos7 网络配置
    django之python3.4及以上连接mysql的一些问题记录
    NetCore log4net 集成以及配置日志信息不重复显示或者记录
    ionic3中关于Ionic ui component使用的一些总结
    ionic2升级到ionic3并打包APK
  • 原文地址:https://www.cnblogs.com/morya/p/2044904.html
Copyright © 2011-2022 走看看