这是一个展示如何通过 HTTP 协议实现简单文件下载功能的示例。以下是关键步骤:

  1. 服务器端配置
    使用 Python 的 http.server 模块创建基础服务:

    from http.server import BaseHTTPRequestHandler, HTTPServer
    import os
    
    class FileDownloader(BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == '/download':
                self.send_response(200)
                self.send_header('Content-type', 'application/octet-stream')
                self.end_headers()
                with open('example.txt', 'rb') as file:
                    self.wfile.write(file.read())
            else:
                self.send_error(404)
    
    if __name__ == '__main__':
        server = HTTPServer(('localhost', 8000), FileDownloader)
        print("Server running on port 8000...")
        server.serve_forever()
    
  2. 客户端请求
    通过浏览器访问 http://localhost:8000/download 即可触发下载。使用工具如 Postman 可更灵活测试请求头参数。

HTTP_Server

如需了解更基础的 HTTP 示例,请查看 Apply/Examples/Example1