制作HTTP请求

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

这个示例中,我们将创建一个带有按钮的简单UI,按下该按钮时将发送对指定网址的HTTP请求。

准备场景

Create a new empty scene, add a CanvasLayer as the root node and add a script to it. Then add two child nodes to it: a Button and an HTTPRequest node. You will need to connect the following signals to the CanvasLayer script:

  • Button.pressed: 按下按钮后,我们将发送请求。
  • HTTPRequest.request_completed: 当请求完成后,我们将获取请求的数据作为参数。

../../_images/rest_api_scene.png

编写脚本

下面是我们使其工作所需的所有代码。 该网址指向一个在线API模拟器; 它将返回一个预先定义好的JSON字符串,然后我们将解析它以获取对数据的访问权限。

  1. extends CanvasLayer
  2. func _ready():
  3. $HTTPRequest.connect("request_completed", self, "_on_request_completed")
  4. func _on_Button_pressed():
  5. $HTTPRequest.request("http://www.mocky.io/v2/5185415ba171ea3a00704eed")
  6. func _on_request_completed(result, response_code, headers, body):
  7. var json = JSON.parse(body.get_string_from_utf8())
  8. print(json.result)

有了这个,您应该在控制台上看到 (hello:world) ; hello是关键字,world是值,两者都是字符串。

有关解析JSON的更多信息,请参阅类型参考 JSONJSONParseResult

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

当然,您也可以设置自定义的HTTP头部。 它们以字符串数组的形式给出,每个字符串都包含一个格式为 "header: value" 的头部。 例如,要设置自定义用户代理(HTTP的 user-agent 头部部分),您可以像这样使用:

  1. $HTTPRequest.request("http://www.mocky.io/v2/5185415ba171ea3a00704eed", ["user-agent: YourCustomUserAgent"])

Please note that, for SSL/TLS encryption and thus HTTPS URLs to work, you may need to take some steps as described here.

此外,在使用授权调用API时,请注意有人可能会分析和反编译已发布的应用程序,因此可能会访问到任何嵌入程序的授权信息,如令牌, 用户名或密码等。 这意味着在游戏中嵌入诸如数据库访问凭证之类的东西通常不是一个好主意。 尽可能避免提供对攻击者有用的信息。

将数据发送到服务器

Until now, we have limited ourselves to requesting data from a server. But what if you need to send data to the server? Here is a common way of doing it:

  1. func _make_post_request(url, data_to_send, use_ssl):
  2. # Convert data to json string:
  3. var query = JSON.print(data_to_send)
  4. # Add 'Content-Type' header:
  5. var headers = ["Content-Type: application/json"]
  6. $HTTPRequest.request(url, headers, use_ssl, HTTPClient.METHOD_POST, query)

请记住,在发送另一个请求之前,您必须等待请求完成。 一次发出多个请求需要每个请求有一个节点。 常见的策略是在运行时根据需要创建和删除HTTPRequest节点。