HTTPRequest 网络请求
可以创建 HTTPRequest 节点,在其上挂载脚本,也可以创建一个全局脚本来使用 httprequest 类,内部使用的是 HTTPClient 类。
注意 1: 导出到 Android 平台时,请务必在导出项目或使用一键部署之前,在 Android 导出预设中启用 INTERNET(网络访问)权限。否则,Android 系统会拦截任何形式的网络通信。
注意 2: HTTPRequest 节点会自动处理响应体(response bodies)的解压缩。除非你已经手动指定了,否则引擎会自动为你发出的每一个请求添加一个 Accept-Encoding 请求头。因此,任何带有 Content-Encoding: gzip 响应头的返回数据,都会被自动解压缩,并以未压缩的字节形式直接交给你。
示例: 调用一个 REST API 并打印其返回的其中一个字段
func _ready():
# 创建一个 HTTP 请求节点,并连接它的完成信号。
var http_request = HTTPRequest.new()
add_child(http_request)
http_request.request_completed.connect(self._http_request_completed)
# 执行一个 GET 请求。编写(这段代码)时,下方的 URL 会返回 JSON 格式的数据。
var error = http_request.request("https://httpbin.org/get")
if error != OK:
push_error("An error occurred in the HTTP request.")
# 执行一个 POST 请求。编写(这段代码)时,下方的 URL 会返回 JSON 格式的数据。
# 注意:不要使用单个 HTTPRequest 节点同时发起多个请求。
# 下面提供的代码片段仅供参考。
var body = JSON.stringify({"name": "Godette"})
error = http_request.request("https://httpbin.org/post", [], HTTPClient.METHOD_POST, body)
if error != OK:
push_error("An error occurred in the HTTP request.")
# 当 HTTP 请求完成时被调用。
func _http_request_completed(result, response_code, headers, body):
var json = JSON.new()
json.parse(body.get_string_from_utf8())
var response = json.get_data()
# 将打印出 HTTPRequest 节点所使用的用户代理字符串(该字符串由 httpbin.org 识别)。
print(response.headers["User-Agent"])
示例: 使用 HTTPRequest 加载一张图片并显示它
func _ready():
# 创建一个 HTTP 请求节点,并连接它的完成信号。
var http_request = HTTPRequest.new()
add_child(http_request)
http_request.request_completed.connect(self._http_request_completed)
# 执行 HTTP 请求。编写(这段代码)时,下方的 URL 会返回一张 PNG 格式的图片。
var error = http_request.request("https://placehold.co/512.png")
if error != OK:
push_error("An error occurred in the HTTP request.")
# 当 HTTP 请求完成时被调用。
func _http_request_completed(result, response_code, headers, body):
if result != HTTPRequest.RESULT_SUCCESS:
push_error("Image couldn't be downloaded. Try a different image.")
var image = Image.new()
var error = image.load_png_from_buffer(body)
if error != OK:
push_error("Couldn't load the image.")
var texture = ImageTexture.create_from_image(image)
# 在 TextureRect 节点中显示这张图片。
var texture_rect = TextureRect.new()
add_child(texture_rect)
texture_rect.texture = texture