进行 HTTP 请求

为什么使用 HTTP?

HTTP 请求可以用来与 Web 服务器以及其他非 Godot 程序通信。

与 Godot 的其他网络功能(例如高阶多人游戏)相比,HTTP 请求的额外开销更大,起步也更慢,所以并不适合实时通信,也不善于进行多人游戏中常见的大量较小更新的发送。

HTTP, however, offers interoperability with external web resources and is great at sending and receiving large amounts of data, for example to transfer files like game assets. These assets can then be loaded using runtime file loading and saving.

所以 HTTP 可以用在游戏的登录系统、大厅浏览器,可以从 Web 获取信息,也可以下载游戏资产。

本教学假设你对Godot和Godot编辑器有一定的了解。请参阅 IntroductionStep by step 教学课程,特别是其 Nodes and ScenesCreating your first script 页面。

Godot 中的 HTTP 请求

在Godot中, 用 HTTPRequest 节点发出HTTP请求是最简单的方法. 它继承自更低级别的 HTTPClient , 相关的教程见 here.

对于此示例,我们将向GitHub发出HTTP请求以检索最新Godot版本的名称。

警告

When exporting to Android, make sure to enable the Internet permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by the Android OS.

准备场景

Create a new empty scene, add a root Node and add a script to it. Then add an HTTPRequest node as a child.

../../_images/rest_api_scene.webp

编写请求脚本

当项目启动时(所以在 _ready() 中),我们将使用 HTTPRequest 节点向Github发送HTTP请求,一旦请求完成,我们就将解析传回的JSON数据,搜寻 name 字段并将其打印到控制台。

GDScriptC#

  1. extends Node
  2. func _ready():
  3. $HTTPRequest.request_completed.connect(_on_request_completed)
  4. $HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest")
  5. func _on_request_completed(result, response_code, headers, body):
  6. var json = JSON.parse_string(body.get_string_from_utf8())
  7. print(json["name"])
  1. using Godot;
  2. using System.Text;
  3. public partial class MyNode : Node
  4. {
  5. public override void _Ready()
  6. {
  7. HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
  8. httpRequest.RequestCompleted += OnRequestCompleted;
  9. httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");
  10. }
  11. private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
  12. {
  13. Godot.Collections.Dictionary json = Json.ParseString(Encoding.UTF8.GetString(body)).AsGodotDictionary();
  14. GD.Print(json["name"]);
  15. }
  16. }

保存脚本和场景,然后运行项目。Github上最新的Godot版本的名称应该打印到输出日志中。有关解析JSON的更多信息,请参阅类引用 JSON

请注意, 你可能需要检查 result 是否等于 RESULT_SUCCESS 以及JSON解析错误是否发生, 要了解更多信息, 请参阅JSON类型参考和 HTTPRequest .

You have to wait for a request to finish before sending another one. Making multiple request at once requires you to have one node per request. A common strategy is to create and delete HTTPRequest nodes at runtime as necessary.

向服务器发送数据

到目前为止, 我们仅限于从服务器上请求数据. 但如果你需要向服务器发送数据呢?这里有一个常见的方法:

GDScriptC#

  1. var json = JSON.stringify(data_to_send)
  2. var headers = ["Content-Type: application/json"]
  3. $HTTPRequest.request(url, headers, HTTPClient.METHOD_POST, json)
  1. string json = Json.Stringify(dataToSend);
  2. string[] headers = new string[] { "Content-Type: application/json" };
  3. HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
  4. httpRequest.Request(url, headers, HttpClient.Method.Post, json);

设置自定义 HTTP 报头

Of course, you can also set custom HTTP headers. These are given as a string array, with each string containing a header in the format "header: value". For example, to set a custom user agent (the HTTP User-Agent header) you could use the following:

GDScriptC#

  1. $HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest", ["User-Agent: YourCustomUserAgent"])
  1. HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
  2. httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest", new string[] { "User-Agent: YourCustomUserAgent" });

警告

Be aware that someone might analyse and decompile your released application and thus may gain access to any embedded authorization information like tokens, usernames or passwords. That means it is usually not a good idea to embed things such as database access credentials inside your game. Avoid providing information useful to an attacker whenever possible.