Godot调用Python HTTP服务器无法获取响应体的原因是什么?
问题:Python HTTP服务器返回的响应体在Godot中为空(状态码200)
我搭建了如下基础Python HTTP服务器:
from http.server import HTTPServer, BaseHTTPRequestHandler import json class ServerHandler(BaseHTTPRequestHandler): def do_POST(self): print("got post") content_len = int(self.headers.get('Content-Length')) print(content_len) post_body = json.loads(self.rfile.read(content_len)) self.send_response(200) self.send_header('Content-type',"application/json") self.end_headers() self.wfile.write(b'{"message":"General Kenobi"}') server= HTTPServer(('',6000),ServerHandler) server.serve_forever() print("server started...")
同时通过Godot的GDScript发送POST请求,代码如下:
tool extends HTTPRequest export (bool) var send_req_btn = false setget send_req func send_req(val): if(val): # Create an HTTP request node and connect its completion signal. var body = to_json({"message": "Hello there"}) var error=self.request("http://localhost:6000", ['Content-Length:'+str(body.length())], true, HTTPClient.METHOD_POST, body) if error != OK: push_error("An error occurred in the HTTP request.") func _on_HTTPRequest_request_completed(result, response_code, headers, body): print("result: ",result) print("response_code: ",response_code) print("headers:",headers) print("body:",body)
请求返回状态码200,但在Godot中打印的响应体为空:
result: 0 response_code: 200 headers:[Server: BaseHTTP/0.6 Python/3.10.4, Date: Thu, 22 Sep 2022 05:47:57 GMT, Content-type: application/json] body:[]
原因分析
问题出在Python服务器没有发送Content-Length响应头。HTTP协议中,客户端需要明确知道响应体的字节长度才能正确读取完整内容,否则无法确定何时停止读取,最终导致返回空的响应体。
修复方案
修改Python服务器的do_POST方法,在发送Content-type头之后添加Content-Length头,值为响应体的字节长度:
def do_POST(self): print("got post") content_len = int(self.headers.get('Content-Length')) print(content_len) post_body = json.loads(self.rfile.read(content_len)) self.send_response(200) self.send_header('Content-type',"application/json") # 添加Content-Length头,指定响应体字节长度 response_body = b'{"message":"General Kenobi"}' self.send_header('Content-Length', str(len(response_body))) self.end_headers() self.wfile.write(response_body)
另外补充:Godot端的代码无需手动设置Content-Length请求头,HTTPRequest会自动根据请求体长度添加该头,可简化为:
var error=self.request("http://localhost:6000", [], true, HTTPClient.METHOD_POST, body)
内容的提问来源于stack exchange,提问作者cak3_lover
相关产品推荐
相关产品推荐

