Advertisement
rfmonk

dl_via_http.py

Jun 30th, 2014
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import argparse
  5. import httplib
  6.  
  7. REMOTE_SERVER_HOST = 'www.python.org'
  8. REMOTE_SERVER_PATH = '/'
  9.  
  10. class HTTPClient:
  11.  
  12.     def __init__(self, host):
  13.         self.host = host
  14.  
  15.     def fetch(self, path):
  16.         http = httplib.HTTP(self.host)
  17.  
  18.  
  19.         # Prepare header
  20.         http.putrequest("GET", path)
  21.         http.putheader("User-Agent", __file__)
  22.         http.putheader("Host", self.host)
  23.         http.putheader("Accept", "*/*")
  24.         http.endheaders()
  25.  
  26.         try:
  27.             errcode, errmsg, headers = http.getreply()
  28.  
  29.         except Exception, e:
  30.             print "Client failed: %s message:%s headers:%s" %(errcode, errmsg, headers)
  31.  
  32.         else:
  33.             print "Got homepage from %s" %self.host
  34.  
  35.         file = http.getfile()
  36.         return file.read()
  37.  
  38.  
  39. if __name__ == "__main__":
  40.     parser = argparse.ArgumentParser(description='HTTP Client Example')
  41.     parser.add_argument('--host', action="store", dest="host", default=REMOTE_SERVER_HOST)
  42.     parser.add_argument('--path', action="store", dest="path", default=REMOTE_SERVER_PATH)
  43.     given_args = parser.parse_args()
  44.     host, path = given_args.host, given_args.path
  45.     client = HTTPClient(host)
  46.     print client.fetch(path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement