Python如何实现 HTTP echo 服务器
更新时间:2025年01月06日 11:36:44 作者:Toormi
本文介绍了如何使用Python实现一个简单的HTTPecho服务器,该服务器支持GET和POST请求,并返回JSON格式的响应,GET请求返回请求路径、方法、头和查询字符串,POST请求还返回请求体内容,服务器的使用方法和测试示例也一并提供,感兴趣的朋友跟随小编一起看看吧
一个用来做测试的简单的 HTTP echo 服务器。
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class EchoHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 构造响应数据
response_data = {
'path': self.path,
'method': 'GET',
'headers': dict(self.headers),
'query_string': self.path.split('?')[1] if '?' in self.path else ''
}
# 设置响应头
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# 发送响应
self.wfile.write(json.dumps(response_data, indent=2).encode())
def do_POST(self):
# 获取请求体长度
content_length = int(self.headers.get('Content-Length', 0))
# 读取请求体
body = self.rfile.read(content_length).decode()
# 构造响应数据
response_data = {
'path': self.path,
'method': 'POST',
'headers': dict(self.headers),
'body': body
}
# 设置响应头
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# 发送响应
self.wfile.write(json.dumps(response_data, indent=2).encode())
def run_server(port=8000):
server_address = ('', port)
httpd = HTTPServer(server_address, EchoHandler)
print(f'Starting server on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run_server()这个 HTTP echo 服务器的特点:
- 支持 GET 和 POST 请求
- 返回 JSON 格式的响应
- 对于 GET 请求,会返回:
- 请求路径
- 请求方法
- 请求头
- 查询字符串
- 对于 POST 请求,额外返回请求体内容
使用方法:
- 运行脚本启动服务器
- 使用浏览器或 curl 访问
http://localhost:8000
测试示例:
# GET 请求 curl http://localhost:8000/test?foo=bar # POST 请求 curl -X POST -d "hello=world" http://localhost:8000/test
到此这篇关于Python实现一个简单的 HTTP echo 服务器的文章就介绍到这了,更多相关Python HTTP echo 服务器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python3中configparser模块读写ini文件并解析配置的用法详解
这篇文章主要介绍了Python3中configparser模块读写ini文件并解析配置的用法详解,需要的朋友可以参考下2020-02-02
使用Python的DrissionPage库设置代理IP的详细流程
DrissionPage 是一个基于 Playwright 和 Requests 的高效网页抓取工具,它简化了 Web 自动化、浏览器操作和抓取任务,通过 DrissionPage,用户可以轻松地使用代理 IP 来隐藏真实的请求来源,本文给大家介绍了如何使用Python的DrissionPage库设置代理IP2025-07-07


最新评论