HTTPRequest
2026/4/14大约 5 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — HTTPRequest
HTTPRequest
定义
HTTPRequest 是 Godot 提供的一个节点,用来向服务器发送 HTTP 网络请求并接收响应。就像你在浏览器地址栏输入网址按回车一样——你告诉它"去这个网址拿数据",它就去把数据拿回来给你。
打个比方:HTTPRequest 就像一个快递员。你给他一个地址(URL),告诉他要寄什么东西(请求体),他就跑一趟把结果带回来。你可以让他去拿东西(GET 请求)、送东西过去(POST 请求)、或者删除东西(DELETE 请求)。
在实际游戏开发中,HTTPRequest 用于:从服务器拉取排行榜数据、向服务器提交玩家分数、下载远程资源、调用 REST API 等。
常用方法
| 方法 | 返回值 | 说明 |
|---|---|---|
Request(url) | Error | 向指定 URL 发送 GET 请求 |
Request(url, customHeaders, method, requestData) | Error | 发送完整的 HTTP 请求,可自定义请求头、方法和请求体 |
CancelRequest() | void | 取消正在进行的请求 |
GetResponseBodySize() | int | 获取响应体大小(字节) |
GetDownloadedBytes() | int | 获取已下载的字节数 |
常用信号
| 信号 | 参数 | 说明 |
|---|---|---|
request_completed | result, code, headers, body | 请求完成时触发,包含响应数据 |
代码示例
基础用法:发送 GET 请求获取数据
C#
using Godot;
public partial class ApiClient : Node
{
private HTTPRequest _httpRequest;
public override void _Ready()
{
_httpRequest = new HTTPRequest();
AddChild(_httpRequest);
_httpRequest.RequestCompleted += OnRequestCompleted;
// 发送 GET 请求
Error err = _httpRequest.Request("https://api.example.com/data");
if (err != Error.Ok)
{
GD.Print($"请求发送失败:{err}");
}
// 运行结果: 请求发送到指定 URL,等待响应
}
private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
{
if (result == (long)HTTPRequest.Result.Success)
{
string jsonStr = body.GetStringFromUtf8();
GD.Print($"响应内容:{jsonStr}");
// 运行结果: 打印服务器返回的 JSON 数据
}
else
{
GD.Print($"请求失败,结果码:{result}");
}
}
}GDScript
extends Node
var _http_request: HTTPRequest
func _ready():
_http_request = HTTPRequest.new()
add_child(_http_request)
_http_request.request_completed.connect(_on_request_completed)
# 发送 GET 请求
var err = _http_request.request("https://api.example.com/data")
if err != OK:
print("请求发送失败:%s" % err)
# 运行结果: 请求发送到指定 URL,等待响应
func _on_request_completed(result, code, headers, body):
if result == HTTPRequest.RESULT_SUCCESS:
var json_str = body.get_string_from_utf8()
print("响应内容:%s" % json_str)
# 运行结果: 打印服务器返回的 JSON 数据
else:
print("请求失败,结果码:%s" % result)实际场景:向服务器提交玩家分数(POST 请求)
C#
using Godot;
using System.Text.Json;
public partial class Leaderboard : Node
{
private HTTPRequest _httpRequest;
public override void _Ready()
{
_httpRequest = new HTTPRequest();
AddChild(_httpRequest);
_httpRequest.RequestCompleted += OnScoreSubmitted;
}
public void SubmitScore(string playerName, int score)
{
// 构造 JSON 请求体
var data = new { name = playerName, score = score };
string jsonBody = JsonSerializer.Serialize(data);
// 发送 POST 请求
string[] headers = { "Content-Type: application/json" };
Error err = _httpRequest.Request(
"https://api.example.com/scores",
headers,
HTTPClient.Method.Post,
jsonBody
);
// 运行结果: 向服务器发送包含玩家名和分数的 POST 请求
GD.Print($"提交分数:{playerName} = {score}");
}
private void OnScoreSubmitted(long result, long code, string[] headers, byte[] body)
{
if (code == 200)
{
GD.Print("分数提交成功!");
// 运行结果: 服务器确认分数已保存
}
else
{
GD.Print($"分数提交失败,状态码:{code}");
}
}
}GDScript
extends Node
var _http_request: HTTPRequest
func _ready():
_http_request = HTTPRequest.new()
add_child(_http_request)
_http_request.request_completed.connect(_on_score_submitted)
func submit_score(player_name: String, score: int):
# 构造 JSON 请求体
var json_body = JSON.stringify({"name": player_name, "score": score})
# 发送 POST 请求
var headers = ["Content-Type: application/json"]
var err = _http_request.request(
"https://api.example.com/scores",
headers,
HTTPClient.METHOD_POST,
json_body
)
# 运行结果: 向服务器发送包含玩家名和分数的 POST 请求
print("提交分数:%s = %d" % [player_name, score])
func _on_score_submitted(result, code, headers, body):
if code == 200:
print("分数提交成功!")
# 运行结果: 服务器确认分数已保存
else:
print("分数提交失败,状态码:%s" % code)进阶用法:下载远程文件并显示进度
C#
using Godot;
public partial class FileDownloader : Node
{
private HTTPRequest _httpRequest;
private ProgressBar _progressBar;
private Label _statusLabel;
private string _savePath = "user://downloaded_image.png";
public override void _Ready()
{
_httpRequest = new HTTPRequest();
AddChild(_httpRequest);
_httpRequest.RequestCompleted += OnDownloadCompleted;
_progressBar = GetNode<ProgressBar>("ProgressBar");
_statusLabel = GetNode<Label>("StatusLabel");
}
public void DownloadFile(string url)
{
_httpRequest.DownloadFile = _savePath;
Error err = _httpRequest.Request(url);
_statusLabel.Text = "正在下载...";
// 运行结果: 开始下载文件到用户目录
}
public override void _Process(double delta)
{
if (_httpRequest != null)
{
long totalSize = _httpRequest.GetResponseBodySize();
long downloaded = _httpRequest.GetDownloadedBytes();
if (totalSize > 0)
{
float progress = (float)downloaded / totalSize * 100.0f;
_progressBar.Value = progress;
_statusLabel.Text = $"下载进度:{progress:F1}%";
// 运行结果: 进度条和文字实时更新
}
}
}
private void OnDownloadCompleted(long result, long code, string[] headers, byte[] body)
{
if (result == (long)HTTPRequest.Result.Success)
{
_statusLabel.Text = "下载完成!";
GD.Print($"文件已保存到:{_savePath}");
// 运行结果: 文件下载完毕并保存
}
}
}GDScript
extends Node
var _http_request: HTTPRequest
@onready var _progress_bar: ProgressBar = $ProgressBar
@onready var _status_label: Label = $StatusLabel
var _save_path: String = "user://downloaded_image.png"
func _ready():
_http_request = HTTPRequest.new()
add_child(_http_request)
_http_request.request_completed.connect(_on_download_completed)
func download_file(url: String):
_http_request.download_file = _save_path
var err = _http_request.request(url)
_status_label.text = "正在下载..."
# 运行结果: 开始下载文件到用户目录
func _process(delta):
if _http_request:
var total_size = _http_request.get_response_body_size()
var downloaded = _http_request.get_downloaded_bytes()
if total_size > 0:
var progress = float(downloaded) / total_size * 100.0
_progress_bar.value = progress
_status_label.text = "下载进度:%.1f%%" % progress
# 运行结果: 进度条和文字实时更新
func _on_download_completed(result, code, headers, body):
if result == HTTPRequest.RESULT_SUCCESS:
_status_label.text = "下载完成!"
print("文件已保存到:%s" % _save_path)
# 运行结果: 文件下载完毕并保存注意事项
- 必须在场景树中:HTTPRequest 节点必须添加到场景树中才能工作。如果你在代码中创建它,记得用
AddChild()添加。 - 同一时间只能处理一个请求:每个 HTTPRequest 实例同时只能处理一个请求。如果需要并发多个请求,需要创建多个 HTTPRequest 节点。
- 线程安全:HTTPRequest 在后台线程执行网络操作,不会阻塞主线程。回调会在主线程执行,可以安全地更新 UI。
- CORS 限制:在 Web 导出中,HTTP 请求受浏览器的跨域策略(CORS)限制。服务器需要正确设置 CORS 头。
- HTTPS:默认支持 HTTPS。在导出版本中需要确保包含 TLS 证书。
