http_request_class.rst 6.0 KB

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