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)