在Python中,可以使用http.server
模塊和json
模塊來創建一個簡單的HTTP服務器,該服務器可以響應80端口上的/query
POST請求,并且請求體為JSON格式。
需要注意,在Linux系統上,使用低于1024的端口(如80端口)需要root權限。
示例代碼:
import http.server
import socketserver
import json# 自定義請求處理類
class MyHandler(http.server.SimpleHTTPRequestHandler):def do_POST(self):if self.path == '/query':# 獲取請求體的長度content_length = int(self.headers['Content-Length'])# 讀取請求體post_data = self.rfile.read(content_length)try:# 解析JSON數據json_data = json.loads(post_data.decode('utf-8'))# 打印接收到的JSON數據print("Received JSON data:", json_data)# 發送響應頭self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()# 構造響應數據response_data = {'message': 'JSON data received successfully'}# 將響應數據轉換為JSON字符串并發送self.wfile.write(json.dumps(response_data).encode('utf-8'))except json.JSONDecodeError:# 若JSON解析失敗,發送400錯誤響應self.send_error(400, 'Bad Request: Invalid JSON data')else:# 若請求路徑不是/query,發送404錯誤響應self.send_error(404, 'Not Found')# 服務器的端口號
PORT = 80with socketserver.TCPServer(("", PORT), MyHandler) as httpd:print(f"Serving at port {PORT}")try:# 啟動服務器httpd.serve_forever()except KeyboardInterrupt:print("Server stopped by user.")
代碼說明:
- 自定義請求處理類
MyHandler
:繼承自http.server.SimpleHTTPRequestHandler
,并重寫do_POST
方法來處理POST請求。 - 處理
/query
請求:- 獲取請求體的長度,并讀取請求體。
- 嘗試解析JSON數據,如果解析成功,打印接收到的JSON數據,并返回一個包含成功消息的JSON響應。
- 如果JSON解析失敗,返回400錯誤響應。
- 處理其他請求:如果請求路徑不是
/query
,返回404錯誤響應。 - 啟動服務器:使用
socketserver.TCPServer
創建一個TCP服務器,并在指定的端口上啟動。
運行代碼:
在Linux系統上,需要以root權限運行該腳本(修改端口至1024以上就不需要root):
sudo python3 server.py
測試服務器:
使用curl
命令來測試服務器:
curl -X POST -H "Content-Type: application/json" -d '{"key": "value"}' http://localhost/query
這樣,服務器將接收并解析JSON數據,并返回一個成功消息。