Table of Contents

Class HttpClient

Namespace
Godot
Assembly
GodotSharp.dll

Hyper-text transfer protocol client (sometimes called "User Agent"). Used to make HTTP requests to download web content, upload files and other data or to communicate with various services, among other use cases.

See the HttpRequest node for a higher-level alternative.

Note: This client only needs to connect to a host once (see ConnectToHost(string, int, TlsOptions)) to send multiple requests. Because of this, methods that take URLs usually take just the part after the host instead of the full URL, as the client is already connected to a host. See Request(Method, string, string[], string) for a full example and to get started.

A HttpClient should be reused between multiple requests or to connect to different hosts instead of creating one client per request. Supports Transport Layer Security (TLS), including server certificate verification. HTTP status codes in the 2xx range indicate success, 3xx redirection (i.e. "try again, but over here"), 4xx something was wrong with the request, and 5xx something went wrong on the server's side.

For more information on HTTP, see MDN's documentation on HTTP (or read RFC 2616 to get it straight from the source).

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.

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.

Note: When performing HTTP requests from a project exported to Web, keep in mind the remote server may not allow requests from foreign origins due to CORS. If you host the server in question, you should modify its backend to allow requests from foreign origins by adding the Access-Control-Allow-Origin: * HTTP header.

Note: TLS support is currently limited to TLS 1.0, TLS 1.1, and TLS 1.2. Attempting to connect to a TLS 1.3-only server will return an error.

Warning: TLS certificate revocation and certificate pinning are currently not supported. Revoked certificates are accepted as long as they are otherwise valid. If this is a concern, you may want to use automatically managed certificates with a short validity period.

[GodotClassName("HTTPClient")]
public class HttpClient : RefCounted, IDisposable
Inheritance
HttpClient
Implements
Inherited Members

Constructors

HttpClient()

public HttpClient()

Properties

BlockingModeEnabled

If true, execution will block until all data is read from the response.

public bool BlockingModeEnabled { get; set; }

Property Value

bool

Connection

The connection to use for this client.

public StreamPeer Connection { get; set; }

Property Value

StreamPeer

ReadChunkSize

The size of the buffer used and maximum bytes to read per iteration. See ReadResponseBodyChunk().

public int ReadChunkSize { get; set; }

Property Value

int

Methods

Close()

Closes the current connection, allowing reuse of this HttpClient.

public void Close()

ConnectToHost(string, int, TlsOptions)

Connects to a host. This needs to be done before any requests are sent.

If no port is specified (or -1 is used), it is automatically set to 80 for HTTP and 443 for HTTPS. You can pass the optional tlsOptions parameter to customize the trusted certification authorities, or the common name verification when using HTTPS. See Client(X509Certificate, string) and ClientUnsafe(X509Certificate).

public Error ConnectToHost(string host, int port = -1, TlsOptions tlsOptions = null)

Parameters

host string
port int
tlsOptions TlsOptions

Returns

Error

GetResponseBodyLength()

Returns the response's 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.

Note: This function always returns -1 on the Web platform due to browsers limitations.

public long GetResponseBodyLength()

Returns

long

GetResponseCode()

Returns the response's HTTP status code.

public int GetResponseCode()

Returns

int

GetResponseHeaders()

Returns the response headers.

public string[] GetResponseHeaders()

Returns

string[]

GetResponseHeadersAsDictionary()

Returns all response headers as a Dictionary of structure { "key": "value1; value2" } where the case-sensitivity of the keys and values is kept like the server delivers it. A value is a simple String, this string can have more than one value where "; " is used as separator.

Example:

{
      "content-length": 12,
      "Content-Type": "application/json; charset=UTF-8",
  }
public Dictionary GetResponseHeadersAsDictionary()

Returns

Dictionary

GetStatus()

Returns a HttpClient.Status constant. Need to call Poll() in order to get status updates.

public HttpClient.Status GetStatus()

Returns

HttpClient.Status

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_name

Name of the method to check for.

Returns

bool

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_name

Name of the signal to check for.

Returns

bool

HasResponse()

If true, this HttpClient has a response available.

public bool HasResponse()

Returns

bool

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_name

Name of the method to invoke.

args NativeVariantPtrArgs

Arguments to use with the invoked method.

ret godot_variant

Value returned by the invoked method.

Returns

bool

IsResponseChunked()

If true, this HttpClient has a response that is chunked.

public bool IsResponseChunked()

Returns

bool

Poll()

This needs to be called in order to have any request processed. Check results with GetStatus().

public Error Poll()

Returns

Error

QueryStringFromDict(Dictionary)

Generates a GET/POST application/x-www-form-urlencoded style query string from a provided dictionary, e.g.:

var fields = new Godot.Collections.Dictionary { { "username", "user" }, { "password", "pass" } };
  string queryString = httpClient.QueryStringFromDict(fields);
  // Returns "username=user&password=pass"

Furthermore, if a key has a null value, only the key itself is added, without equal sign and value. If the value is an array, for each value in it a pair with the same key is added.

var fields = new Godot.Collections.Dictionary
  {
      { "single", 123 },
      { "notValued", default },
      { "multiple", new Godot.Collections.Array { 22, 33, 44 } },
  };
  string queryString = httpClient.QueryStringFromDict(fields);
  // Returns "single=123&not_valued&multiple=22&multiple=33&multiple=44"
public string QueryStringFromDict(Dictionary fields)

Parameters

fields Dictionary

Returns

string

ReadResponseBodyChunk()

Reads one chunk from the response.

public byte[] ReadResponseBodyChunk()

Returns

byte[]

Request(Method, string, string[], string)

Sends a request to the connected host.

The URL parameter is usually just the part after the host, so for https://somehost.com/index.php, it is /index.php. When sending requests to an HTTP proxy server, it should be an absolute URL. For Options requests, * is also allowed. For Connect requests, it should be the authority component (host:port).

Headers are HTTP request headers. For available HTTP methods, see HttpClient.Method.

To create a POST request with query strings to push to the server, do:

var fields = new Godot.Collections.Dictionary { { "username", "user" }, { "password", "pass" } };
  string queryString = new HttpClient().QueryStringFromDict(fields);
  string[] headers = { "Content-Type: application/x-www-form-urlencoded", $"Content-Length: {queryString.Length}" };
  var result = new HttpClient().Request(HttpClient.Method.Post, "index.php", headers, queryString);

Note: The body parameter is ignored if method is Get. This is because GET methods can't contain request data. As a workaround, you can pass request data as a query string in the URL. See String.uri_encode for an example.

public Error Request(HttpClient.Method method, string url, string[] headers, string body = "")

Parameters

method HttpClient.Method
url string
headers string[]
body string

Returns

Error

RequestRaw(Method, string, string[], byte[])

Sends a raw request to the connected host.

The URL parameter is usually just the part after the host, so for https://somehost.com/index.php, it is /index.php. When sending requests to an HTTP proxy server, it should be an absolute URL. For Options requests, * is also allowed. For Connect requests, it should be the authority component (host:port).

Headers are HTTP request headers. For available HTTP methods, see HttpClient.Method.

Sends the body data raw, as a byte array and does not encode it in any way.

public Error RequestRaw(HttpClient.Method method, string url, string[] headers, byte[] body)

Parameters

method HttpClient.Method
url string
headers string[]
body byte[]

Returns

Error

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

host string
port int

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

host string
port int