http_request_class.rst 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. .. _doc_http_request_class:
  2. Making HTTP requests
  3. ====================
  4. Why use HTTP?
  5. -------------
  6. `HTTP requests <https://developer.mozilla.org/en-US/docs/Web/HTTP>`_ are useful
  7. to communicate with web servers and other non-Godot programs.
  8. Compared to Godot's other networking features (like
  9. :ref:`High-level multiplayer <doc_high_level_multiplayer>`),
  10. HTTP requests have more overhead and take more time to get going,
  11. so they aren't suited for real-time communication, and aren't great to send
  12. lots of small updates as is common for multiplayer gameplay.
  13. HTTP, however, offers interoperability with external
  14. web resources and is great at sending and receiving large amounts
  15. of data, for example to transfer files like game assets. These assets can then
  16. be loaded using
  17. :ref:`runtime file loading and saving <doc_runtime_loading_and_saving>`.
  18. So HTTP may be useful for your game's login system, lobby browser,
  19. to retrieve some information from the web or to download game assets.
  20. This tutorial assumes some familiarity with Godot and the Godot Editor.
  21. Refer to the :ref:`Introduction <toc-learn-introduction>` and the
  22. :ref:`Step by step <toc-learn-step_by_step>` tutorial, especially its
  23. :ref:`Nodes and Scenes <doc_nodes_and_scenes>` and
  24. :ref:`Creating your first script <doc_scripting_first_script>` pages if needed.
  25. HTTP requests in Godot
  26. ----------------------
  27. The :ref:`HTTPRequest <class_HTTPRequest>` node is the easiest way to make HTTP requests in Godot.
  28. It is backed by the more low-level :ref:`HTTPClient <class_HTTPClient>`,
  29. for which a tutorial is available :ref:`here <doc_http_client_class>`.
  30. For this example, we will make an HTTP request to GitHub to retrieve the name
  31. of the latest Godot release.
  32. .. warning::
  33. When exporting to **Android**, make sure to enable the **Internet**
  34. permission in the Android export preset before exporting the project or
  35. using one-click deploy. Otherwise, network communication of any kind will be
  36. blocked by the Android OS.
  37. Preparing the scene
  38. -------------------
  39. Create a new empty scene, add a root :ref:`Node <class_Node>` and add a script to it.
  40. Then add an :ref:`HTTPRequest <class_HTTPRequest>` node as a child.
  41. .. image:: img/rest_api_scene.webp
  42. Scripting the request
  43. ---------------------
  44. When the project is started (so in ``_ready()``), we're going to send an HTTP request
  45. to Github using our :ref:`HTTPRequest <class_HTTPRequest>` node,
  46. and once the request completes, we're going to parse the returned JSON data,
  47. look for the ``name`` field and print that to console.
  48. .. tabs::
  49. .. code-tab:: gdscript GDScript
  50. extends Node
  51. func _ready():
  52. $HTTPRequest.request_completed.connect(_on_request_completed)
  53. $HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest")
  54. func _on_request_completed(result, response_code, headers, body):
  55. var json = JSON.parse_string(body.get_string_from_utf8())
  56. print(json["name"])
  57. .. code-tab:: csharp
  58. using Godot;
  59. using System.Text;
  60. public partial class MyNode : Node
  61. {
  62. public override void _Ready()
  63. {
  64. HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
  65. httpRequest.RequestCompleted += OnRequestCompleted;
  66. httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");
  67. }
  68. private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
  69. {
  70. Godot.Collections.Dictionary json = Json.ParseString(Encoding.UTF8.GetString(body)).AsGodotDictionary();
  71. GD.Print(json["name"]);
  72. }
  73. }
  74. Save the script and the scene, and run the project.
  75. The name of the most recent Godot release on Github should be printed to the output log.
  76. For more information on parsing JSON, see the class references for :ref:`JSON <class_JSON>`.
  77. Note that you may want to check whether the ``result`` equals ``RESULT_SUCCESS``
  78. and whether a JSON parsing error occurred, see the JSON class reference and
  79. :ref:`HTTPRequest <class_HTTPRequest>` for more.
  80. You have to wait for a request to finish before sending another one.
  81. Making multiple request at once requires you to have one node per request.
  82. A common strategy is to create and delete HTTPRequest nodes at runtime as necessary.
  83. Sending data to the server
  84. --------------------------
  85. Until now, we have limited ourselves to requesting data from a server.
  86. But what if you need to send data to the server? Here is a common way of doing it:
  87. .. tabs::
  88. .. code-tab:: gdscript GDScript
  89. var json = JSON.stringify(data_to_send)
  90. var headers = ["Content-Type: application/json"]
  91. $HTTPRequest.request(url, headers, HTTPClient.METHOD_POST, json)
  92. .. code-tab:: csharp
  93. string json = Json.Stringify(dataToSend);
  94. string[] headers = new string[] { "Content-Type: application/json" };
  95. HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
  96. httpRequest.Request(url, headers, HttpClient.Method.Post, json);
  97. Setting custom HTTP headers
  98. ---------------------------
  99. Of course, you can also set custom HTTP headers. These are given as a string array,
  100. with each string containing a header in the format ``"header: value"``.
  101. For example, to set a custom user agent (the HTTP ``User-Agent`` header) you could use the following:
  102. .. tabs::
  103. .. code-tab:: gdscript GDScript
  104. $HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest", ["User-Agent: YourCustomUserAgent"])
  105. .. code-tab:: csharp
  106. HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
  107. httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest", new string[] { "User-Agent: YourCustomUserAgent" });
  108. .. danger::
  109. Be aware that someone might analyse and decompile your released application and
  110. thus may gain access to any embedded authorization information like tokens, usernames or passwords.
  111. That means it is usually not a good idea to embed things such as database
  112. access credentials inside your game. Avoid providing information useful to an attacker whenever possible.