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.
Checking the stable version of the documentation...
HTTPRequest
Un nodo con la capacità di inviare richieste HTTP(S).
Descrizione
A node with the ability to send HTTP requests. Uses HTTPClient internally.
Can be used to make HTTP requests, i.e. download or upload files or web content via HTTP.
Warning: See the notes and warnings on HTTPClient for limitations, especially regarding TLS security.
Note: 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 Android.
Example: Contact a REST API and print one of its returned fields:
func _ready():
# Create an HTTP request node and connect its completion signal.
var http_request = HTTPRequest.new()
add_child(http_request)
http_request.request_completed.connect(self._http_request_completed)
# Perform a GET request. The URL below returns JSON as of writing.
var error = http_request.request("https://httpbin.org/get")
if error != OK:
push_error("An error occurred in the HTTP request.")
# Perform a POST request. The URL below returns JSON as of writing.
# Note: Don't make simultaneous requests using a single HTTPRequest node.
# The snippet below is provided for reference only.
var body = JSON.stringify({"name": "Godette"})
error = http_request.request("https://httpbin.org/post", [], HTTPClient.METHOD_POST, body)
if error != OK:
push_error("An error occurred in the HTTP request.")
# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
var json = JSON.new()
json.parse(body.get_string_from_utf8())
var response = json.get_data()
# Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
print(response.headers["User-Agent"])
public override void _Ready()
{
// Create an HTTP request node and connect its completion signal.
var httpRequest = new HttpRequest();
AddChild(httpRequest);
httpRequest.RequestCompleted += HttpRequestCompleted;
// Perform a GET request. The URL below returns JSON as of writing.
Error error = httpRequest.Request("https://httpbin.org/get");
if (error != Error.Ok)
{
GD.PushError("An error occurred in the HTTP request.");
}
// Perform a POST request. The URL below returns JSON as of writing.
// Note: Don't make simultaneous requests using a single HTTPRequest node.
// The snippet below is provided for reference only.
string body = Json.Stringify(new Godot.Collections.Dictionary
{
{ "name", "Godette" }
});
error = httpRequest.Request("https://httpbin.org/post", null, HttpClient.Method.Post, body);
if (error != Error.Ok)
{
GD.PushError("An error occurred in the HTTP request.");
}
}
// Called when the HTTP request is completed.
private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
{
var json = new Json();
json.Parse(body.GetStringFromUtf8());
var response = json.GetData().AsGodotDictionary();
// Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
GD.Print((response["headers"].AsGodotDictionary())["User-Agent"]);
}
Example: Load an image using HTTPRequest and display it:
func _ready():
# Create an HTTP request node and connect its completion signal.
var http_request = HTTPRequest.new()
add_child(http_request)
http_request.request_completed.connect(self._http_request_completed)
# Perform the HTTP request. The URL below returns a PNG image as of writing.
var error = http_request.request("https://placehold.co/512.png")
if error != OK:
push_error("An error occurred in the HTTP request.")
# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
if result != HTTPRequest.RESULT_SUCCESS:
push_error("Image couldn't be downloaded. Try a different image.")
var image = Image.new()
var error = image.load_png_from_buffer(body)
if error != OK:
push_error("Couldn't load the image.")
var texture = ImageTexture.create_from_image(image)
# Display the image in a TextureRect node.
var texture_rect = TextureRect.new()
add_child(texture_rect)
texture_rect.texture = texture
public override void _Ready()
{
// Create an HTTP request node and connect its completion signal.
var httpRequest = new HttpRequest();
AddChild(httpRequest);
httpRequest.RequestCompleted += HttpRequestCompleted;
// Perform the HTTP request. The URL below returns a PNG image as of writing.
Error error = httpRequest.Request("https://placehold.co/512.png");
if (error != Error.Ok)
{
GD.PushError("An error occurred in the HTTP request.");
}
}
// Called when the HTTP request is completed.
private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
{
if (result != (long)HttpRequest.Result.Success)
{
GD.PushError("Image couldn't be downloaded. Try a different image.");
}
var image = new Image();
Error error = image.LoadPngFromBuffer(body);
if (error != Error.Ok)
{
GD.PushError("Couldn't load the image.");
}
var texture = ImageTexture.CreateFromImage(image);
// Display the image in a TextureRect node.
var textureRect = new TextureRect();
AddChild(textureRect);
textureRect.Texture = texture;
}
Note: HTTPRequest nodes will automatically handle decompression of response bodies. An Accept-Encoding header will be automatically added to each of your requests, unless one is already specified. Any response with a Content-Encoding: gzip header will automatically be decompressed and delivered to you as uncompressed bytes.
Tutorial
Proprietà
|
||
|
||
|
||
|
||
|
||
|
||
|
Metodi
void |
|
get_body_size() const |
|
get_downloaded_bytes() const |
|
get_http_client_status() const |
|
request(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data: String = "") |
|
request_raw(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data_raw: PackedByteArray = PackedByteArray()) |
|
void |
set_http_proxy(host: String, port: int) |
void |
set_https_proxy(host: String, port: int) |
void |
set_tls_options(client_options: TLSOptions) |
Segnali
request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) 🔗
Emesso quando una richiesta è completata.
Enumerazioni
enum Result: 🔗
Result RESULT_SUCCESS = 0
Richiesta riuscita.
Result RESULT_CHUNKED_BODY_SIZE_MISMATCH = 1
Richiesta non riuscita a causa di una mancata corrispondenza tra la dimensione del corpo in blocchi prevista e quella effettiva durante il trasferimento. Le possibili cause includono errori di rete, configurazione errata del server o problemi con la codifica in blocchi.
Result RESULT_CANT_CONNECT = 2
Richiesta fallita durante la connessione.
Result RESULT_CANT_RESOLVE = 3
Richiesta fallita durante la risoluzione.
Result RESULT_CONNECTION_ERROR = 4
Richiesta fallita a causa di un errore di connessione (lettura/scrittura).
Result RESULT_TLS_HANDSHAKE_ERROR = 5
Richiesta fallita durante l'handshake TLS.
Result RESULT_NO_RESPONSE = 6
La richiesta non ha (ancora) una risposta.
Result RESULT_BODY_SIZE_LIMIT_EXCEEDED = 7
La richiesta ha superato il limite massimo di dimensione, vedi body_size_limit.
Result RESULT_BODY_DECOMPRESS_FAILED = 8
Richiesta non riuscita a causa di un errore durante la decompressione del corpo della risposta. Le possibili cause includono un formato di compressione non supportato o non corretto, dati danneggiati o trasferimento incompleto.
Result RESULT_REQUEST_FAILED = 9
Richiesta fallita (attualmente inutilizzata).
Result RESULT_DOWNLOAD_FILE_CANT_OPEN = 10
HTTPRequest non è riuscito ad aprire il file scaricato.
Result RESULT_DOWNLOAD_FILE_WRITE_ERROR = 11
HTTPRequest non è riuscito a scrivere sul file scaricato.
Result RESULT_REDIRECT_LIMIT_REACHED = 12
La richiesta ha raggiunto il limite massimo di reindirizzamenti, vedi max_redirects.
Result RESULT_TIMEOUT = 13
Richiesta non riuscita a causa di un timeout. Se prevedi che le richieste impiegheranno molto tempo, prova ad aumentare il valore di timeout o a impostarlo su 0.0 per rimuovere completamente il timeout.
Descrizioni delle proprietà
Se true, questa intestazione sarà aggiunta a ogni richiesta: Accept-Encoding: gzip, deflate la quale indica ai server che è possibile comprimere i corpi delle risposte.
Qualsiasi corpo della risposta che dichiara un Content-Encoding di gzip o deflate sarà automaticamente decompresso e i byte non compressi saranno consegnati tramite request_completed.
Se l'utente ha specificato la propria intestazione Accept-Encoding, nessuna intestazione sarà aggiunta indipendentemente da accept_gzip.
Se false nessuna intestazione sarà aggiunta e nessuna decompressione sarà effettuata sui corpi delle risposte. I byte grezzi del corpo della risposta saranno restituiti tramite request_completed.
Dimensione massima consentita per i corpi delle risposte. Se il corpo della risposta è compresso, ciò sarà utilizzato come dimensione massima consentita per il corpo decompresso.
int download_chunk_size = 65536 🔗
La dimensione del buffer utilizzato e il numero massimo di byte da leggere per ogni iterazione. Vedi HTTPClient.read_chunk_size.
Imposta questo su un valore inferiore (ad esempio 4096 per 4 KiB) quando si scaricano piccoli file per ridurre l'utilizzo di memoria a scapito della velocità di download.
Il file in cui scaricare. Invierà qualsiasi file ricevuto in esso.
Numero massimo di reindirizzamenti consentiti.
The duration to wait before a request times out, in seconds (independent of Engine.time_scale). If timeout is set to 0.0, the request will never time out.
For simple requests, such as communication with a REST API, it is recommended to set timeout to a value suitable for the server response time (commonly between 1.0 and 10.0). This will help prevent unwanted timeouts caused by variation in response times while still allowing the application to detect when a request has timed out. For larger requests such as file downloads, it is recommended to set timeout to 0.0, disabling the timeout functionality. This will help prevent large transfers from failing due to exceeding the timeout value.
Se true, il multithreading è utilizzato per migliorare le prestazioni.
Descrizioni dei metodi
void cancel_request() 🔗
Annulla la richiesta in corso.
Restituisce la lunghezza del corpo della risposta.
Nota: Alcuni server Web potrebbero non inviare una lunghezza del corpo. In questo caso, il valore restituito sarà -1. Anche se si utilizza la codifica di trasferimento in blocchi, la lunghezza del corpo sarà -1.
int get_downloaded_bytes() const 🔗
Restituisce il numero di byte scaricati da questa HTTPRequest.
Status get_http_client_status() const 🔗
Restituisce lo stato attuale del HTTPClient sottostante.
Error request(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data: String = "") 🔗
Crea una richiesta sul HTTPClient sottostante. Se non ci sono errori di configurazione, prova a connettersi tramite HTTPClient.connect_to_host() e passa i parametri a HTTPClient.request().
Restituisce @GlobalScope.OK se la richiesta è stata creata correttamente. (Non significa che il server abbia risposto), @GlobalScope.ERR_UNCONFIGURED se non è nell'albero, @GlobalScope.ERR_BUSY se sta ancora elaborando la richiesta precedente, @GlobalScope.ERR_INVALID_PARAMETER se la stringa fornita non è un formato URL valido o @GlobalScope.ERR_CANT_CONNECT se non sta usando un thread e HTTPClient non riesce a connettersi all'host.
Nota: Quando method è HTTPClient.METHOD_GET, il payload inviato tramite request_data potrebbe essere ignorato dal server o addirittura causare la richiesta a essere rifiutata dal server (controlla RFC 7231 sezione 4.3.1 per maggiori dettagli). Come alternativa, è possibile inviare i dati come stringa di richiesta nell'URL (vedi String.uri_encode() per un esempio).
Nota: Si consiglia di utilizzare la crittografia di trasporto (TLS) ed evitare di inviare informazioni sensibili (come le credenziali di accesso) nei parametri URL HTTP GET. Considera di utilizzare richieste HTTP POST o intestazioni HTTP per tali informazioni.
Error request_raw(url: String, custom_headers: PackedStringArray = PackedStringArray(), method: Method = 0, request_data_raw: PackedByteArray = PackedByteArray()) 🔗
Crea una richiesta sul sottostante HTTPClient utilizzando un array grezzo di byte per il corpo della richiesta. Se non ci sono errori di configurazione, prova a connettersi tramite HTTPClient.connect_to_host() e passa i parametri a HTTPClient.request().
Restituisce @GlobalScope.OK se la richiesta è stata creata correttamente. (Non significa che il server abbia risposto), @GlobalScope.ERR_UNCONFIGURED se non è nell'albero, @GlobalScope.ERR_BUSY se sta ancora elaborando la richiesta precedente, @GlobalScope.ERR_INVALID_PARAMETER se la stringa fornita non è un formato URL valido o @GlobalScope.ERR_CANT_CONNECT se non utilizza un thread e HTTPClient non riesce a connettersi all'host.
void set_http_proxy(host: String, port: int) 🔗
Imposta il server proxy per le richieste HTTP.
Il server proxy non è impostato se host è vuoto o port è -1.
void set_https_proxy(host: String, port: int) 🔗
Imposta il server proxy per le richieste HTTPS.
Il server proxy non è impostato se host è vuoto o port è -1.
void set_tls_options(client_options: TLSOptions) 🔗
Imposta le TLSOptions da utilizzare quando ci si connette a un server HTTPS. Vedi TLSOptions.client().