• 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)
    

      

  • 相关阅读:
    poj 3087 直接模拟
    POJ-3126 BFS,埃式筛选及黑科技
    POJ3278-Catch That Cow
    js变量提升
    饿了么
    2分钟就能学会的【Google/百度搜索大法】了解一下?
    span标签间距
    Vue移动端项目如何使用手机预览调试
    Port 3000 is already in use
    koa2第一天 async详解
  • 原文地址:https://www.cnblogs.com/ssooking/p/5879793.html
Copyright © 2020-2023  润新知