python httplib模塊使用實(shí)例

字號(hào):


    httplib模塊是一個(gè)底層基礎(chǔ)模塊,實(shí)現(xiàn)的功能比較少,正常情況下比較少用到.推薦用urllib, urllib2, httplib2.
    httpconnection 對(duì)象
    class httplib.httpconnection(host[, port[, strict[, timeout[, source_address]]]])
    創(chuàng)建httpconnection對(duì)象
    httpconnection.request(method, url[, body[, headers]])
    發(fā)送請(qǐng)求
    httpconnection.getresponse()
    獲得響應(yīng)
    httpresponse對(duì)象
    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
    獲得頭內(nèi)容
    httpresponse.version
    獲得頭http版本
    httpresponse.status
    獲得返回狀態(tài)碼
    httpresponse.reason
    獲得返回說明
    實(shí)例
    代碼如下:
    #!/usr/bin/python
    import httplib
    conn = httplib.httpconnection()
    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