Debian Codegraph @

doc/classes/HTTPRequest.xml

raw symbols SCIP
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <class name="HTTPRequest" inherits="Node" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
3 <brief_description>
4 A node with the ability to send HTTP(S) requests.
5 </brief_description>
6 <description>
7 A node with the ability to send HTTP requests. Uses [HTTPClient] internally.
8 Can be used to make HTTP requests, i.e. download or upload files or web content via HTTP.
9 [b]Warning:[/b] See the notes and warnings on [HTTPClient] for limitations, especially regarding TLS security.
10 [b]Note:[/b] When exporting to Android, make sure to enable the [code]INTERNET[/code] 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.
11 [b]Example:[/b] Contact a REST API and print one of its returned fields:
12 [codeblocks]
13 [gdscript]
14 func _ready():
15 # Create an HTTP request node and connect its completion signal.
16 var http_request = HTTPRequest.new()
17 add_child(http_request)
18 http_request.request_completed.connect(self._http_request_completed)
19
20 # Perform a GET request. The URL below returns JSON as of writing.
21 var error = http_request.request("https://httpbin.org/get")
22 if error != OK:
23 push_error("An error occurred in the HTTP request.")
24
25 # Perform a POST request. The URL below returns JSON as of writing.
26 # Note: Don't make simultaneous requests using a single HTTPRequest node.
27 # The snippet below is provided for reference only.
28 var body = JSON.new().stringify({"name": "Godette"})
29 error = http_request.request("https://httpbin.org/post", [], HTTPClient.METHOD_POST, body)
30 if error != OK:
31 push_error("An error occurred in the HTTP request.")
32
33 # Called when the HTTP request is completed.
34 func _http_request_completed(result, response_code, headers, body):
35 var json = JSON.new()
36 json.parse(body.get_string_from_utf8())
37 var response = json.get_data()
38
39 # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
40 print(response.headers["User-Agent"])
41 [/gdscript]
42 [csharp]
43 public override void _Ready()
44 {
45 // Create an HTTP request node and connect its completion signal.
46 var httpRequest = new HttpRequest();
47 AddChild(httpRequest);
48 httpRequest.RequestCompleted += HttpRequestCompleted;
49
50 // Perform a GET request. The URL below returns JSON as of writing.
51 Error error = httpRequest.Request("https://httpbin.org/get");
52 if (error != Error.Ok)
53 {
54 GD.PushError("An error occurred in the HTTP request.");
55 }
56
57 // Perform a POST request. The URL below returns JSON as of writing.
58 // Note: Don't make simultaneous requests using a single HTTPRequest node.
59 // The snippet below is provided for reference only.
60 string body = new Json().Stringify(new Godot.Collections.Dictionary
61 {
62 { "name", "Godette" }
63 });
64 error = httpRequest.Request("https://httpbin.org/post", null, HttpClient.Method.Post, body);
65 if (error != Error.Ok)
66 {
67 GD.PushError("An error occurred in the HTTP request.");
68 }
69 }
70
71 // Called when the HTTP request is completed.
72 private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
73 {
74 var json = new Json();
75 json.Parse(body.GetStringFromUtf8());
76 var response = json.GetData().AsGodotDictionary();
77
78 // Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
79 GD.Print((response["headers"].AsGodotDictionary())["User-Agent"]);
80 }
81 [/csharp]
82 [/codeblocks]
83 [b]Example:[/b] Load an image using [HTTPRequest] and display it:
84 [codeblocks]
85 [gdscript]
86 func _ready():
87 # Create an HTTP request node and connect its completion signal.
88 var http_request = HTTPRequest.new()
89 add_child(http_request)
90 http_request.request_completed.connect(self._http_request_completed)
91
92 # Perform the HTTP request. The URL below returns a PNG image as of writing.
93 var error = http_request.request("https://placehold.co/512.png")
94 if error != OK:
95 push_error("An error occurred in the HTTP request.")
96
97 # Called when the HTTP request is completed.
98 func _http_request_completed(result, response_code, headers, body):
99 if result != HTTPRequest.RESULT_SUCCESS:
100 push_error("Image couldn't be downloaded. Try a different image.")
101
102 var image = Image.new()
103 var error = image.load_png_from_buffer(body)
104 if error != OK:
105 push_error("Couldn't load the image.")
106
107 var texture = ImageTexture.create_from_image(image)
108
109 # Display the image in a TextureRect node.
110 var texture_rect = TextureRect.new()
111 add_child(texture_rect)
112 texture_rect.texture = texture
113 [/gdscript]
114 [csharp]
115 public override void _Ready()
116 {
117 // Create an HTTP request node and connect its completion signal.
118 var httpRequest = new HttpRequest();
119 AddChild(httpRequest);
120 httpRequest.RequestCompleted += HttpRequestCompleted;
121
122 // Perform the HTTP request. The URL below returns a PNG image as of writing.
123 Error error = httpRequest.Request("https://placehold.co/512.png");
124 if (error != Error.Ok)
125 {
126 GD.PushError("An error occurred in the HTTP request.");
127 }
128 }
129
130 // Called when the HTTP request is completed.
131 private void HttpRequestCompleted(long result, long responseCode, string[] headers, byte[] body)
132 {
133 if (result != (long)HttpRequest.Result.Success)
134 {
135 GD.PushError("Image couldn't be downloaded. Try a different image.");
136 }
137 var image = new Image();
138 Error error = image.LoadPngFromBuffer(body);
139 if (error != Error.Ok)
140 {
141 GD.PushError("Couldn't load the image.");
142 }
143
144 var texture = ImageTexture.CreateFromImage(image);
145
146 // Display the image in a TextureRect node.
147 var textureRect = new TextureRect();
148 AddChild(textureRect);
149 textureRect.Texture = texture;
150 }
151 [/csharp]
152 [/codeblocks]
153 [b]Note:[/b] [HTTPRequest] nodes will automatically handle decompression of response bodies. An [code]Accept-Encoding[/code] header will be automatically added to each of your requests, unless one is already specified. Any response with a [code]Content-Encoding: gzip[/code] header will automatically be decompressed and delivered to you as uncompressed bytes.
154 </description>
155 <tutorials>
156 <link title="Making HTTP requests">$DOCS_URL/tutorials/networking/http_request_class.html</link>
157 <link title="TLS certificates">$DOCS_URL/tutorials/networking/ssl_certificates.html</link>
158 </tutorials>
159 <methods>
160 <method name="cancel_request">
161 <return type="void" />
162 <description>
163 Cancels the current request.
164 </description>
165 </method>
166 <method name="get_body_size" qualifiers="const">
167 <return type="int" />
168 <description>
169 Returns the response body length.
170 [b]Note:[/b] Some Web servers may not send a body length. In this case, the value returned will be [code]-1[/code]. If using chunked transfer encoding, the body length will also be [code]-1[/code].
171 </description>
172 </method>
173 <method name="get_downloaded_bytes" qualifiers="const">
174 <return type="int" />
175 <description>
176 Returns the number of bytes this HTTPRequest downloaded.
177 </description>
178 </method>
179 <method name="get_http_client_status" qualifiers="const">
180 <return type="int" enum="HTTPClient.Status" />
181 <description>
182 Returns the current status of the underlying [HTTPClient].
183 </description>
184 </method>
185 <method name="request">
186 <return type="int" enum="Error" />
187 <param index="0" name="url" type="String" />
188 <param index="1" name="custom_headers" type="PackedStringArray" default="PackedStringArray()" />
189 <param index="2" name="method" type="int" enum="HTTPClient.Method" default="0" />
190 <param index="3" name="request_data" type="String" default="&quot;&quot;" />
191 <description>
192 Creates request on the underlying [HTTPClient]. If there is no configuration errors, it tries to connect using [method HTTPClient.connect_to_host] and passes parameters onto [method HTTPClient.request].
193 Returns [constant OK] if request is successfully created. (Does not imply that the server has responded), [constant ERR_UNCONFIGURED] if not in the tree, [constant ERR_BUSY] if still processing previous request, [constant ERR_INVALID_PARAMETER] if given string is not a valid URL format, or [constant ERR_CANT_CONNECT] if not using thread and the [HTTPClient] cannot connect to host.
194 [b]Note:[/b] When [param method] is [constant HTTPClient.METHOD_GET], the payload sent via [param request_data] might be ignored by the server or even cause the server to reject the request (check [url=https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.1]RFC 7231 section 4.3.1[/url] for more details). As a workaround, you can send data as a query string in the URL (see [method String.uri_encode] for an example).
195 [b]Note:[/b] 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.
196 </description>
197 </method>
198 <method name="request_raw">
199 <return type="int" enum="Error" />
200 <param index="0" name="url" type="String" />
201 <param index="1" name="custom_headers" type="PackedStringArray" default="PackedStringArray()" />
202 <param index="2" name="method" type="int" enum="HTTPClient.Method" default="0" />
203 <param index="3" name="request_data_raw" type="PackedByteArray" default="PackedByteArray()" />
204 <description>
205 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 [method HTTPClient.connect_to_host] and passes parameters onto [method HTTPClient.request].
206 Returns [constant OK] if request is successfully created. (Does not imply that the server has responded), [constant ERR_UNCONFIGURED] if not in the tree, [constant ERR_BUSY] if still processing previous request, [constant ERR_INVALID_PARAMETER] if given string is not a valid URL format, or [constant ERR_CANT_CONNECT] if not using thread and the [HTTPClient] cannot connect to host.
207 </description>
208 </method>
209 <method name="set_http_proxy">
210 <return type="void" />
211 <param index="0" name="host" type="String" />
212 <param index="1" name="port" type="int" />
213 <description>
214 Sets the proxy server for HTTP requests.
215 The proxy server is unset if [param host] is empty or [param port] is -1.
216 </description>
217 </method>
218 <method name="set_https_proxy">
219 <return type="void" />
220 <param index="0" name="host" type="String" />
221 <param index="1" name="port" type="int" />
222 <description>
223 Sets the proxy server for HTTPS requests.
224 The proxy server is unset if [param host] is empty or [param port] is -1.
225 </description>
226 </method>
227 <method name="set_tls_options">
228 <return type="void" />
229 <param index="0" name="client_options" type="TLSOptions" />
230 <description>
231 Sets the [TLSOptions] to be used when connecting to an HTTPS server. See [method TLSOptions.client].
232 </description>
233 </method>
234 </methods>
235 <members>
236 <member name="accept_gzip" type="bool" setter="set_accept_gzip" getter="is_accepting_gzip" default="true">
237 If [code]true[/code], this header will be added to each request: [code]Accept-Encoding: gzip, deflate[/code] telling servers that it's okay to compress response bodies.
238 Any Response body declaring a [code]Content-Encoding[/code] of either [code]gzip[/code] or [code]deflate[/code] will then be automatically decompressed, and the uncompressed bytes will be delivered via [signal request_completed].
239 If the user has specified their own [code]Accept-Encoding[/code] header, then no header will be added regardless of [member accept_gzip].
240 If [code]false[/code] 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 [signal request_completed].
241 </member>
242 <member name="body_size_limit" type="int" setter="set_body_size_limit" getter="get_body_size_limit" default="-1">
243 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.
244 </member>
245 <member name="download_chunk_size" type="int" setter="set_download_chunk_size" getter="get_download_chunk_size" default="65536">
246 The size of the buffer used and maximum bytes to read per iteration. See [member HTTPClient.read_chunk_size].
247 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.
248 </member>
249 <member name="download_file" type="String" setter="set_download_file" getter="get_download_file" default="&quot;&quot;">
250 The file to download into. Will output any received file into it.
251 </member>
252 <member name="max_redirects" type="int" setter="set_max_redirects" getter="get_max_redirects" default="8">
253 Maximum number of allowed redirects.
254 </member>
255 <member name="timeout" type="float" setter="set_timeout" getter="get_timeout" default="0.0">
256 The duration to wait before a request times out, in seconds (independent of [member Engine.time_scale]). If [member timeout] is set to [code]0.0[/code], the request will never time out.
257 For simple requests, such as communication with a REST API, it is recommended to set [member timeout] to a value suitable for the server response time (commonly between [code]1.0[/code] and [code]10.0[/code]). 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 [member timeout] to [code]0.0[/code], disabling the timeout functionality. This will help prevent large transfers from failing due to exceeding the timeout value.
258 </member>
259 <member name="use_threads" type="bool" setter="set_use_threads" getter="is_using_threads" default="false">
260 If [code]true[/code], multithreading is used to improve performance.
261 </member>
262 </members>
263 <signals>
264 <signal name="request_completed">
265 <param index="0" name="result" type="int" />
266 <param index="1" name="response_code" type="int" />
267 <param index="2" name="headers" type="PackedStringArray" />
268 <param index="3" name="body" type="PackedByteArray" />
269 <description>
270 Emitted when a request is completed.
271 </description>
272 </signal>
273 </signals>
274 <constants>
275 <constant name="RESULT_SUCCESS" value="0" enum="Result">
276 Request successful.
277 </constant>
278 <constant name="RESULT_CHUNKED_BODY_SIZE_MISMATCH" value="1" enum="Result">
279 Request failed due to a mismatch between the expected and actual chunked body size during transfer. Possible causes include network errors, server misconfiguration, or issues with chunked encoding.
280 </constant>
281 <constant name="RESULT_CANT_CONNECT" value="2" enum="Result">
282 Request failed while connecting.
283 </constant>
284 <constant name="RESULT_CANT_RESOLVE" value="3" enum="Result">
285 Request failed while resolving.
286 </constant>
287 <constant name="RESULT_CONNECTION_ERROR" value="4" enum="Result">
288 Request failed due to connection (read/write) error.
289 </constant>
290 <constant name="RESULT_TLS_HANDSHAKE_ERROR" value="5" enum="Result">
291 Request failed on TLS handshake.
292 </constant>
293 <constant name="RESULT_NO_RESPONSE" value="6" enum="Result">
294 Request does not have a response (yet).
295 </constant>
296 <constant name="RESULT_BODY_SIZE_LIMIT_EXCEEDED" value="7" enum="Result">
297 Request exceeded its maximum size limit, see [member body_size_limit].
298 </constant>
299 <constant name="RESULT_BODY_DECOMPRESS_FAILED" value="8" enum="Result">
300 Request failed due to an error while decompressing the response body. Possible causes include unsupported or incorrect compression format, corrupted data, or incomplete transfer.
301 </constant>
302 <constant name="RESULT_REQUEST_FAILED" value="9" enum="Result">
303 Request failed (currently unused).
304 </constant>
305 <constant name="RESULT_DOWNLOAD_FILE_CANT_OPEN" value="10" enum="Result">
306 HTTPRequest couldn't open the download file.
307 </constant>
308 <constant name="RESULT_DOWNLOAD_FILE_WRITE_ERROR" value="11" enum="Result">
309 HTTPRequest couldn't write to the download file.
310 </constant>
311 <constant name="RESULT_REDIRECT_LIMIT_REACHED" value="12" enum="Result">
312 Request reached its maximum redirect limit, see [member max_redirects].
313 </constant>
314 <constant name="RESULT_TIMEOUT" value="13" enum="Result">
315 Request failed due to a timeout. If you expect requests to take a long time, try increasing the value of [member timeout] or setting it to [code]0.0[/code] to remove the timeout completely.
316 </constant>
317 </constants>
318 </class>