Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Fare richieste HTTP

Why use HTTP?

HTTP requests are useful to communicate with web servers and other non-Godot programs.

Compared to Godot's other networking features (like 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. These assets can then be loaded using runtime file loading and saving.

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.

Richieste HTTP in Godot

The HTTPRequest node is the easiest way to make HTTP requests in Godot. It is backed by the more low-level HTTPClient, for which a tutorial is available here.

For this example, we will make an HTTP request to GitHub to retrieve the name of the latest Godot release.

Avvertimento

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.

Preparare la scena

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

Programmare la richiesta

When the project is started (so in _ready()), we're going to send an HTTP request to Github using our 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.

extends Node

func _ready():
    $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):
    var json = JSON.parse_string(body.get_string_from_utf8())
    print(json["name"])

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 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 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.

Inviare dati al 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:

var json = JSON.stringify(data_to_send)
var headers = ["Content-Type: application/json"]
$HTTPRequest.request(url, headers, HTTPClient.METHOD_POST, json)

Impostare intestazioni HTTP personalizzate

Naturalmente, è anche possibile impostare intestazioni HTTP personalizzate. Queste sono fornite come array di stringhe, ciascuna contenente un'intestazione nel formato "intestazione: valore". Ad esempio, per impostare un user agent personalizzato (l'intestazione HTTP User-Agent), è possibile utilizzare quanto segue:

$HTTPRequest.request("https://api.github.com/repos/godotengine/godot/releases/latest", ["User-Agent: YourCustomUserAgent"])

Pericolo

Tieni presente che qualcuno potrebbe analizzare e decompilare la tua applicazione rilasciata e quindi ottenere l'accesso a qualsiasi informazione di autorizzazione incorporata, come token, nomi utente o password. Ciò significa che di solito non è una buona idea incorporare elementi come le credenziali di accesso ai database all'interno del tuo gioco. Evita di fornire informazioni utili a un aggressore, ove possibile.