Class HttpRequest
- Namespace
- Godot
- Assembly
- GodotSharp.dll
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 of contacting a REST API and printing one of its returned fields:
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 = new 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 of loading and displaying an image using HTTPRequest:
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://via.placeholder.com/512");
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;
}
Gzipped response bodies: HTTPRequest will automatically handle decompression of response bodies. A 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.
[GodotClassName("HTTPRequest")]
public class HttpRequest : Node, IDisposable
- Inheritance
-
HttpRequest
- Implements
- Inherited Members
Constructors
HttpRequest()
public HttpRequest()
Properties
AcceptGZip
If true
, this header will be added to each request: Accept-Encoding: gzip, deflate
telling servers that it's okay to compress response bodies.
Any Response body declaring a Content-Encoding
of either gzip
or deflate
will then be automatically decompressed, and the uncompressed bytes will be delivered via RequestCompleted.
If the user has specified their own Accept-Encoding
header, then no header will be added regardless of AcceptGZip.
If false
no header will be added, and no decompression will be performed on response bodies. The raw bytes of the response body will be returned via RequestCompleted.
public bool AcceptGZip { get; set; }
Property Value
BodySizeLimit
Maximum allowed size for response bodies. If the response body is compressed, this will be used as the maximum allowed size for the decompressed body.
public int BodySizeLimit { get; set; }
Property Value
DownloadChunkSize
The size of the buffer used and maximum bytes to read per iteration. See ReadChunkSize.
Set this to a lower value (e.g. 4096 for 4 KiB) when downloading small files to decrease memory usage at the cost of download speeds.
public int DownloadChunkSize { get; set; }
Property Value
DownloadFile
The file to download into. Will output any received file into it.
public string DownloadFile { get; set; }
Property Value
MaxRedirects
Maximum number of allowed redirects.
public int MaxRedirects { get; set; }
Property Value
Timeout
The duration to wait in seconds before a request times out. If Timeout is set to 0.0
then the request will never time out. For simple requests, such as communication with a REST API, it is recommended that Timeout is set to a value suitable for the server response time (e.g. between 1.0
and 10.0
). This will help prevent unwanted timeouts caused by variation in server response times while still allowing the application to detect when a request has timed out. For larger requests such as file downloads it is suggested the Timeout be set to 0.0
, disabling the timeout functionality. This will help to prevent large transfers from failing due to exceeding the timeout value.
public double Timeout { get; set; }
Property Value
UseThreads
If true
, multithreading is used to improve performance.
public bool UseThreads { get; set; }
Property Value
Methods
CancelRequest()
Cancels the current request.
public void CancelRequest()
GetBodySize()
Returns the response body length.
Note: Some Web servers may not send a body length. In this case, the value returned will be -1
. If using chunked transfer encoding, the body length will also be -1
.
public int GetBodySize()
Returns
GetDownloadedBytes()
Returns the number of bytes this HTTPRequest downloaded.
public int GetDownloadedBytes()
Returns
GetHttpClientStatus()
Returns the current status of the underlying HttpClient. See HttpClient.Status.
public HttpClient.Status GetHttpClientStatus()
Returns
HasGodotClassMethod(in godot_string_name)
Check if the type contains a method with the given name. This method is used by Godot to check if a method exists before invoking it. Do not call or override this method.
protected override bool HasGodotClassMethod(in godot_string_name method)
Parameters
method
godot_string_nameName of the method to check for.
Returns
HasGodotClassSignal(in godot_string_name)
Check if the type contains a signal with the given name. This method is used by Godot to check if a signal exists before raising it. Do not call or override this method.
protected override bool HasGodotClassSignal(in godot_string_name signal)
Parameters
signal
godot_string_nameName of the signal to check for.
Returns
InvokeGodotClassMethod(in godot_string_name, NativeVariantPtrArgs, out godot_variant)
Invokes the method with the given name, using the given arguments. This method is used by Godot to invoke methods from the engine side. Do not call or override this method.
protected override bool InvokeGodotClassMethod(in godot_string_name method, NativeVariantPtrArgs args, out godot_variant ret)
Parameters
method
godot_string_nameName of the method to invoke.
args
NativeVariantPtrArgsArguments to use with the invoked method.
ret
godot_variantValue returned by the invoked method.
Returns
Request(string, string[], Method, string)
Creates request on the underlying HttpClient. If there is no configuration errors, it tries to connect using ConnectToHost(string, int, TlsOptions) and passes parameters onto Request(Method, string, string[], string).
Returns Ok if request is successfully created. (Does not imply that the server has responded), Unconfigured if not in the tree, Busy if still processing previous request, InvalidParameter if given string is not a valid URL format, or CantConnect if not using thread and the HttpClient cannot connect to host.
Note: When method
is Get, the payload sent via requestData
might be ignored by the server or even cause the server to reject the request (check RFC 7231 section 4.3.1 for more details). As a workaround, you can send data as a query string in the URL (see String.uri_encode
for an example).
Note: It's recommended to use transport encryption (TLS) and to avoid sending sensitive information (such as login credentials) in HTTP GET URL parameters. Consider using HTTP POST requests or HTTP headers for such information instead.
public Error Request(string url, string[] customHeaders = null, HttpClient.Method method = Method.Get, string requestData = "")
Parameters
url
stringcustomHeaders
string[]If the parameter is null, then the default value is
Array.Empty<string>()
.method
HttpClient.MethodrequestData
string
Returns
RequestRaw(string, string[], Method, byte[])
Creates request on the underlying HttpClient using a raw array of bytes for the request body. If there is no configuration errors, it tries to connect using ConnectToHost(string, int, TlsOptions) and passes parameters onto Request(Method, string, string[], string).
Returns Ok if request is successfully created. (Does not imply that the server has responded), Unconfigured if not in the tree, Busy if still processing previous request, InvalidParameter if given string is not a valid URL format, or CantConnect if not using thread and the HttpClient cannot connect to host.
public Error RequestRaw(string url, string[] customHeaders = null, HttpClient.Method method = Method.Get, byte[] requestDataRaw = null)
Parameters
url
stringcustomHeaders
string[]If the parameter is null, then the default value is
Array.Empty<string>()
.method
HttpClient.MethodrequestDataRaw
byte[]If the parameter is null, then the default value is
Array.Empty<byte>()
.
Returns
SetHttpProxy(string, int)
Sets the proxy server for HTTP requests.
The proxy server is unset if host
is empty or port
is -1.
public void SetHttpProxy(string host, int port)
Parameters
SetHttpsProxy(string, int)
Sets the proxy server for HTTPS requests.
The proxy server is unset if host
is empty or port
is -1.
public void SetHttpsProxy(string host, int port)
Parameters
SetTlsOptions(TlsOptions)
Sets the TlsOptions to be used when connecting to an HTTPS server. See Client(X509Certificate, string).
public void SetTlsOptions(TlsOptions clientOptions)
Parameters
clientOptions
TlsOptions
Events
RequestCompleted
Emitted when a request is completed.
public event HttpRequest.RequestCompletedEventHandler RequestCompleted