浏览代码

Merge pull request #7183 from mhilbrunner/http-docs

Update HTTP docs for Godot 4
Max Hilbrunner 2 年之前
父节点
当前提交
4cc818f793
共有 3 个文件被更改,包括 87 次插入64 次删除
  1. 87 64
      tutorials/networking/http_request_class.rst
  2. 二进制
      tutorials/networking/img/rest_api_scene.png
  3. 二进制
      tutorials/networking/img/rest_api_scene.webp

+ 87 - 64
tutorials/networking/http_request_class.rst

@@ -1,70 +1,91 @@
-:article_outdated: True
-
 .. _doc_http_request_class:
 .. _doc_http_request_class:
 
 
 Making HTTP requests
 Making HTTP requests
 ====================
 ====================
 
 
+Why use HTTP?
+-------------
+
+`HTTP requests <https://developer.mozilla.org/en-US/docs/Web/HTTP>`_ are useful
+to communicate with web servers and other non-Godot programs.
+
+Compared to Godot's other networking features (like
+:ref:`High-level multiplayer <doc_high_level_multiplayer>`),
+HTTP requests have more overhead and take more time to get going,
+so they aren't suited for real-time communication, and aren't great to send
+lots of small updates as is common for multiplayer gameplay.
+
+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.
+
+So HTTP may be useful for your game's login system, lobby browser,
+to retrieve some information from the web or to download game assets.
+
+This tutorial assumes some familiarity with Godot and the Godot Editor.
+Refer to the :ref:`Introduction <toc-learn-introduction>` and the
+:ref:`Step by step <toc-learn-step_by_step>` tutorial, especially its
+:ref:`Nodes and Scenes <doc_nodes_and_scenes>` and
+:ref:`Creating your first script <doc_scripting_first_script>` pages if needed.
+
+HTTP requests in Godot
+----------------------
+
 The :ref:`HTTPRequest <class_HTTPRequest>` node is the easiest way to make HTTP requests in Godot.
 The :ref:`HTTPRequest <class_HTTPRequest>` node is the easiest way to make HTTP requests in Godot.
-It is backed by the more low-level :ref:`HTTPClient <class_HTTPClient>`, for which a tutorial is available :ref:`here <doc_http_client_class>`.
+It is backed by the more low-level :ref:`HTTPClient <class_HTTPClient>`,
+for which a tutorial is available :ref:`here <doc_http_client_class>`.
 
 
-For the sake of this example, we will create a simple UI with a button, that when pressed will start the HTTP request to the specified URL.
+For this example, we will make an HTTP request to GitHub to retrieve the name
+of the latest Godot release.
 
 
 .. warning::
 .. warning::
 
 
-    When exporting to Android, make sure to enable the ``INTERNET``
+    When exporting to **Android**, make sure to enable the **Internet**
     permission in the Android export preset before exporting the project or
     permission in the Android export preset before exporting the project or
     using one-click deploy. Otherwise, network communication of any kind will be
     using one-click deploy. Otherwise, network communication of any kind will be
-    blocked by Android.
+    blocked by the Android OS.
 
 
-Preparing scene
----------------
+Preparing the scene
+-------------------
 
 
-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:
+Create a new empty scene, add a root :ref:`Node <class_Node>` and add a script to it.
+Then add a :ref:`HTTPRequest <class_HTTPRequest>` node as a child.
 
 
-- Button.pressed: When the button is pressed, we will start the request.
-- HTTPRequest.request_completed: When the request is completed, we will get the requested data as an argument.
+.. image:: img/rest_api_scene.webp
 
 
-.. image:: img/rest_api_scene.png
+Scripting the request
+---------------------
 
 
-Scripting
----------
-
-Below is all the code we need to make it work. The URL points to an online API mocker; it returns a predefined JSON string, which we will then parse to get access to the data.
+When the project is started (so in ``_ready()``), we're going to send an HTTP request
+to Github using our :ref:`HTTPRequest <class_HTTPRequest>` node,
+and once the request completes, we're going to parse the returned JSON data,
+look for the ``name`` field and print that to console.
 
 
 .. tabs::
 .. tabs::
 
 
     .. code-tab:: gdscript GDScript
     .. code-tab:: gdscript GDScript
 
 
-        extends CanvasLayer
+        extends Node
 
 
         func _ready():
         func _ready():
-            $HTTPRequest.connect("request_completed", self, "_on_request_completed")
-            $Button.connect("pressed", self, "_on_Button_pressed")
-
-        func _on_Button_pressed():
-            $HTTPRequest.request("http://www.mocky.io/v2/5185415ba171ea3a00704eed")
+            $HTTPRequest.request_completed.connect(_on_request_completed)
+            $HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest")
 
 
         func _on_request_completed(result, response_code, headers, body):
         func _on_request_completed(result, response_code, headers, body):
-            var json = JSON.parse(body.get_string_from_utf8())
-            print(json.result)
+            var json = JSON.parse_string(body.get_string_from_utf8())
+            print(json["name"])
 
 
     .. code-tab:: csharp
     .. code-tab:: csharp
 
 
         using Godot;
         using Godot;
-        
-        public partial class MyCanvasLayer : CanvasLayer
+
+        public partial class MyNode : Node
         {
         {
             public override void _Ready()
             public override void _Ready()
             {
             {
                 GetNode("HTTPRequest").RequestCompleted += OnRequestCompleted;
                 GetNode("HTTPRequest").RequestCompleted += OnRequestCompleted;
-                GetNode("Button").Pressed += OnButtonPressed;
-            }
-
-            private void OnButtonPressed()
-            {
                 HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
                 HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
-                httpRequest.Request("http://www.mocky.io/v2/5185415ba171ea3a00704eed");
+                httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest");
             }
             }
 
 
             private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
             private void OnRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
@@ -74,58 +95,60 @@ Below is all the code we need to make it work. The URL points to an online API m
             }
             }
         }
         }
 
 
-With this, you should see ``(hello:world)`` printed on the console; ``hello`` being a key, ``world`` being a value, and both of them are of type :ref:`String <class_string>`.
-
+Save the script and the scene, and run the project.
+The name of the most recent Godot release on Github should be printed to the output log.
 For more information on parsing JSON, see the class references for :ref:`JSON <class_JSON>`.
 For more information on parsing JSON, see the class references for :ref:`JSON <class_JSON>`.
 
 
-Note that you may want to check whether the ``result`` equals ``RESULT_SUCCESS`` and whether a JSON parsing error occurred, see the JSON class reference and :ref:`HTTPRequest <class_HTTPRequest>` for more.
+Note that you may want to check whether the ``result`` equals ``RESULT_SUCCESS``
+and whether a JSON parsing error occurred, see the JSON class reference and
+:ref:`HTTPRequest <class_HTTPRequest>` for more.
+
+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.
 
 
-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:
+Sending data to the server
+--------------------------
+
+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:
 
 
 .. tabs::
 .. tabs::
 
 
     .. code-tab:: gdscript GDScript
     .. code-tab:: gdscript GDScript
 
 
-        $HTTPRequest.request("http://www.mocky.io/v2/5185415ba171ea3a00704eed", ["user-agent: YourCustomUserAgent"])
+        var json = JSON.stringify(data_to_send)
+        var headers = ["Content-Type: application/json"]
+        $HTTPRequest.request(url, headers, HTTPClient.METHOD_POST, json)
 
 
     .. code-tab:: csharp
     .. code-tab:: csharp
 
 
+        string json = Json.Stringify(dataToSend);
+        string[] headers = new string[] { "Content-Type: application/json" };
         HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
         HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
-        httpRequest.Request("http://www.mocky.io/v2/5185415ba171ea3a00704eed", new string[] { "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 :ref:`here <doc_ssl_certificates>`.
-
-Also, when calling APIs using authorization, 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.
+        httpRequest.Request(url, headers, HttpClient.Method.Post, json);
 
 
-Sending data to server
-----------------------
+Setting custom HTTP headers
+---------------------------
 
 
-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:
+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:
 
 
 .. tabs::
 .. tabs::
 
 
     .. code-tab:: gdscript GDScript
     .. code-tab:: gdscript GDScript
 
 
-        func _make_post_request(url, data_to_send, use_ssl):
-            # Convert data to json string:
-            var query = JSON.stringify(data_to_send)
-            # Add 'Content-Type' header:
-            var headers = ["Content-Type: application/json"]
-            $HTTPRequest.request(url, headers, use_ssl, HTTPClient.METHOD_POST, query)
+        $HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest", ["User-Agent: YourCustomUserAgent"])
 
 
     .. code-tab:: csharp
     .. code-tab:: csharp
 
 
-        public void MakePostRequest(string url, Variant dataToSend, bool useSsl)
-        {
-            // Convert data to json string:
-            string query = Json.Stringify(dataToSend);
-            // Add 'Content-Type' header:
-            string[] headers = new string[] { "Content-Type: application/json" };
-            HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
-            httpRequest.Request(url, headers, useSsl, HttpClient.Method.Post, query);
-        }
+        HttpRequest httpRequest = GetNode<HttpRequest>("HTTPRequest");
+        httpRequest.Request("https://api.github.com/repos/godotengine/godot/releases/latest", new string[] { "User-Agent: YourCustomUserAgent" });
 
 
-Keep in mind that 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.
+.. warning::
+
+    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.

二进制
tutorials/networking/img/rest_api_scene.png


二进制
tutorials/networking/img/rest_api_scene.webp