python網絡編程 — HTTP客戶端


A simple http client.

It gets the contents of special webserver page and print it.(Default path is "/")

#!/usr/share/env python
#coding:utf-8

import argparse
import httplib

#設置默認訪問url和端口
REMOTE_SERVER_HOST='www.python.org'
REMOTE_SERVER_PATH='/'


class HTTPClient(object):
    """
        docstring for HTTPClient
        Eg: python HTTPClient.py --host=www.iana.org 
        python HTTPClient.py --host=www.iana.org --path='/domains/reserved'
    """
    def __init__(self, host):
        self.host = host

    def fetch(self,path):
        http = httplib.HTTP(self.host)

        #設置請求頭信息
        http.putrequest("GET",path)
        http.putheader("User-Agent",__file__)
        http.putheader("Host",self.host)
        http.putheader("Accept","*/*")
        http.endheaders()

        try:
            #getreply方法返回service code ,service reseason,RFC82 headers
            errcode,errmsg,headers = http.getreply()
        except Exception,e:
            print "Client failed code: %s message: %s headers: %s" %(errcode,errmsg,headers)
        else:
            print "Got homepage from %s" %self.host

            #打印獲取的內容
            file = http.getfile()
            return file.read()

if __name__ == '__main__':
    parse = argparse.ArgumentParser(description='HTTP Client Example')
    parse.add_argument('--host',action="store",dest="host",default=REMOTE_SERVER_HOST)
    parse.add_argument('--path',action="store",dest="path",default=REMOTE_SERVER_PATH)
    given_args = parse.parse_args()
    host,path = given_args.host,given_args.path
    client = HTTPClient(host)
    print client.fetch(path)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM