Python中如何使用http.server模块接收GET请求并发送POST请求?
我想写个简单程序监听客户端的 http 请求,然后返回一个结果给客户端,请大家帮看下如下思路是否正确:
1.用 Python3 自带的 http.server 来监听
2.客户端用 http get 方法来获取
3.本机程序返回结果用 http post 方法返回给客户端
Python中如何使用http.server模块接收GET请求并发送POST请求?
10 回复
直接用 Flask 写个 api ?
http://www.pythondoc.com/flask-restful/first.html
import http.server
import socketserver
from urllib import request, parse
import json
class CustomHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
"""处理GET请求并转发为POST请求"""
print(f"收到GET请求路径: {self.path}")
# 1. 准备要POST的数据
post_data = {
'original_path': self.path,
'method': 'GET',
'timestamp': '2024-01-01T12:00:00'
}
# 2. 发送POST请求到目标服务器
target_url = 'http://httpbin.org/post' # 测试用的目标地址
try:
# 编码数据
data_bytes = parse.urlencode(post_data).encode('utf-8')
# 创建并发送POST请求
req = request.Request(target_url, data=data_bytes, method='POST')
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
with request.urlopen(req) as response:
post_response = response.read().decode('utf-8')
response_data = json.loads(post_response)
# 3. 将POST响应返回给GET客户端
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# 从响应中提取form数据返回
result = {
'status': 'success',
'received_data': response_data.get('form', {})
}
self.wfile.write(json.dumps(result).encode('utf-8'))
except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'application/json')
self.end_headers()
error_msg = {'error': str(e)}
self.wfile.write(json.dumps(error_msg).encode('utf-8'))
def log_message(self, format, *args):
"""禁用默认日志输出"""
pass
def run_server(port=8000):
"""启动HTTP服务器"""
with socketserver.TCPServer(("", port), CustomHandler) as httpd:
print(f"服务器启动在端口 {port}")
print(f"测试地址: http://localhost:{port}/any/path?param=value")
httpd.serve_forever()
if __name__ == "__main__":
run_server()
代码说明:
- 创建自定义处理器:继承
BaseHTTPRequestHandler,重写do_GET方法处理GET请求 - 接收GET请求:通过
self.path获取请求路径和查询参数 - 构造POST数据:将GET请求信息包装成字典,准备转发
- 发送POST请求:
- 使用
urllib.request.Request创建POST请求 - 设置
data参数和method='POST' - 添加必要的请求头
- 用
urlopen发送请求并获取响应
- 使用
- 返回响应:将POST请求的响应处理后返回给原始GET客户端
测试方法:
- 运行脚本启动服务器
- 浏览器访问
http://localhost:8000/test?name=value - 服务器会将该GET请求转发到
http://httpbin.org/post - 返回处理后的JSON响应
关键点:
do_GET方法专门处理GET请求urllib.request模块用于发送HTTP请求- POST数据需要编码为字节流
- 注意异常处理和响应头设置
这方案适合简单的代理或API网关场景。
http 响应没有 post、get 这一说吧
发送请求你需要 requests 库。
你要发送给客户端 post 请求是为啥? 那客户端还要起一个 server 监听。 直接用 get 请求的 response 不就好了么
你应该先看一下 http 原理…
返回 post 给客户端? 你知道你在说什么吗?
,,,,,,,,,,,,,,
可以,把 http 协议重写就行了
可以告别 cs 了


