HTTPRequest.xml 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <class name="HTTPRequest" inherits="Node" version="4.0">
  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 SSL 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 of contacting a REST API and printing one of its returned fields:[/b]
  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.connect("request_completed", self, "_http_request_completed")
  19. # Perform a GET request. The URL below returns JSON as of writing.
  20. var error = http_request.request("https://httpbin.org/get")
  21. if error != OK:
  22. push_error("An error occurred in the HTTP request.")
  23. # Perform a POST request. The URL below returns JSON as of writing.
  24. # Note: Don't make simultaneous requests using a single HTTPRequest node.
  25. # The snippet below is provided for reference only.
  26. var body = {"name": "Godette"}
  27. error = http_request.request("https://httpbin.org/post", [], true, HTTPClient.METHOD_POST, body)
  28. if error != OK:
  29. push_error("An error occurred in the HTTP request.")
  30. # Called when the HTTP request is completed.
  31. func _http_request_completed(result, response_code, headers, body):
  32. var response = parse_json(body.get_string_from_utf8())
  33. # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
  34. print(response.headers["User-Agent"])
  35. [/gdscript]
  36. [csharp]
  37. public override void _Ready()
  38. {
  39. // Create an HTTP request node and connect its completion signal.
  40. var httpRequest = new HTTPRequest();
  41. AddChild(httpRequest);
  42. httpRequest.Connect("request_completed", this, nameof(HttpRequestCompleted));
  43. // Perform a GET request. The URL below returns JSON as of writing.
  44. Error error = httpRequest.Request("https://httpbin.org/get");
  45. if (error != Error.Ok)
  46. {
  47. GD.PushError("An error occurred in the HTTP request.");
  48. }
  49. // Perform a POST request. The URL below returns JSON as of writing.
  50. // Note: Don't make simultaneous requests using a single HTTPRequest node.
  51. // The snippet below is provided for reference only.
  52. string[] body = { "name", "Godette" };
  53. // GDScript to_json is non existent, so we use JSON.Print() here.
  54. error = httpRequest.Request("https://httpbin.org/post", null, true, HTTPClient.Method.Post, JSON.Print(body));
  55. if (error != Error.Ok)
  56. {
  57. GD.PushError("An error occurred in the HTTP request.");
  58. }
  59. }
  60. // Called when the HTTP request is completed.
  61. private void HttpRequestCompleted(int result, int response_code, string[] headers, byte[] body)
  62. {
  63. // GDScript parse_json is non existent so we have to use JSON.parse, which has a slightly different syntax.
  64. var response = JSON.Parse(body.GetStringFromUTF8()).Result as Godot.Collections.Dictionary;
  65. // Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
  66. GD.Print((response["headers"] as Godot.Collections.Dictionary)["User-Agent"]);
  67. }
  68. [/csharp]
  69. [/codeblocks]
  70. [b]Example of loading and displaying an image using HTTPRequest:[/b]
  71. [codeblocks]
  72. [gdscript]
  73. func _ready():
  74. # Create an HTTP request node and connect its completion signal.
  75. var http_request = HTTPRequest.new()
  76. add_child(http_request)
  77. http_request.connect("request_completed", self, "_http_request_completed")
  78. # Perform the HTTP request. The URL below returns a PNG image as of writing.
  79. var error = http_request.request("https://via.placeholder.com/512")
  80. if error != OK:
  81. push_error("An error occurred in the HTTP request.")
  82. # Called when the HTTP request is completed.
  83. func _http_request_completed(result, response_code, headers, body):
  84. if result != HTTPRequest.RESULT_SUCCESS:
  85. push_error("Image couldn't be downloaded. Try a different image.")
  86. var image = Image.new()
  87. var error = image.load_png_from_buffer(body)
  88. if error != OK:
  89. push_error("Couldn't load the image.")
  90. var texture = ImageTexture.new()
  91. texture.create_from_image(image)
  92. # Display the image in a TextureRect node.
  93. var texture_rect = TextureRect.new()
  94. add_child(texture_rect)
  95. texture_rect.texture = texture
  96. [/gdscript]
  97. [csharp]
  98. public override void _Ready()
  99. {
  100. // Create an HTTP request node and connect its completion signal.
  101. var httpRequest = new HTTPRequest();
  102. AddChild(httpRequest);
  103. httpRequest.Connect("request_completed", this, nameof(HttpRequestCompleted));
  104. // Perform the HTTP request. The URL below returns a PNG image as of writing.
  105. Error error = httpRequest.Request("https://via.placeholder.com/512");
  106. if (error != Error.Ok)
  107. {
  108. GD.PushError("An error occurred in the HTTP request.");
  109. }
  110. }
  111. // Called when the HTTP request is completed.
  112. private void HttpRequestCompleted(int result, int response_code, string[] headers, byte[] body)
  113. {
  114. if (result != (int)HTTPRequest.Result.Success)
  115. {
  116. GD.PushError("Image couldn't be downloaded. Try a different image.");
  117. }
  118. var image = new Image();
  119. Error error = image.LoadPngFromBuffer(body);
  120. if (error != Error.Ok)
  121. {
  122. GD.PushError("Couldn't load the image.");
  123. }
  124. var texture = new ImageTexture();
  125. texture.CreateFromImage(image);
  126. // Display the image in a TextureRect node.
  127. var textureRect = new TextureRect();
  128. AddChild(textureRect);
  129. textureRect.Texture = texture;
  130. }
  131. [/csharp]
  132. [/codeblocks]
  133. [b]Gzipped response bodies[/b]: HTTPRequest will automatically handle decompression of response bodies. A [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.
  134. </description>
  135. <tutorials>
  136. <link title="Making HTTP requests">https://docs.godotengine.org/en/latest/tutorials/networking/http_request_class.html</link>
  137. <link title="SSL certificates">https://docs.godotengine.org/en/latest/tutorials/networking/ssl_certificates.html</link>
  138. </tutorials>
  139. <methods>
  140. <method name="cancel_request">
  141. <return type="void" />
  142. <description>
  143. Cancels the current request.
  144. </description>
  145. </method>
  146. <method name="get_body_size" qualifiers="const">
  147. <return type="int" />
  148. <description>
  149. Returns the response body length.
  150. [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].
  151. </description>
  152. </method>
  153. <method name="get_downloaded_bytes" qualifiers="const">
  154. <return type="int" />
  155. <description>
  156. Returns the amount of bytes this HTTPRequest downloaded.
  157. </description>
  158. </method>
  159. <method name="get_http_client_status" qualifiers="const">
  160. <return type="int" enum="HTTPClient.Status" />
  161. <description>
  162. Returns the current status of the underlying [HTTPClient]. See [enum HTTPClient.Status].
  163. </description>
  164. </method>
  165. <method name="request">
  166. <return type="int" enum="Error" />
  167. <argument index="0" name="url" type="String" />
  168. <argument index="1" name="custom_headers" type="PackedStringArray" default="PackedStringArray()" />
  169. <argument index="2" name="ssl_validate_domain" type="bool" default="true" />
  170. <argument index="3" name="method" type="int" enum="HTTPClient.Method" default="0" />
  171. <argument index="4" name="request_data" type="String" default="&quot;&quot;" />
  172. <description>
  173. 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].
  174. 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.
  175. [b]Note:[/b] When [code]method[/code] is [constant HTTPClient.METHOD_GET], the payload sent via [code]request_data[/code] 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).
  176. [b]Note:[/b] It's recommended to use transport encryption (SSL/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.
  177. </description>
  178. </method>
  179. <method name="request_raw">
  180. <return type="int" enum="Error" />
  181. <argument index="0" name="url" type="String" />
  182. <argument index="1" name="custom_headers" type="PackedStringArray" default="PackedStringArray()" />
  183. <argument index="2" name="ssl_validate_domain" type="bool" default="true" />
  184. <argument index="3" name="method" type="int" enum="HTTPClient.Method" default="0" />
  185. <argument index="4" name="request_data_raw" type="PackedByteArray" default="PackedByteArray()" />
  186. <description>
  187. 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].
  188. 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.
  189. </description>
  190. </method>
  191. </methods>
  192. <members>
  193. <member name="accept_gzip" type="bool" setter="set_accept_gzip" getter="is_accepting_gzip" default="true">
  194. 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.
  195. 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 [code]request_completed[/code].
  196. If the user has specified their own [code]Accept-Encoding[/code] header, then no header will be added regardless of [code]accept_gzip[/code].
  197. 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 [code]request_completed[/code].
  198. </member>
  199. <member name="body_size_limit" type="int" setter="set_body_size_limit" getter="get_body_size_limit" default="-1">
  200. 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.
  201. </member>
  202. <member name="download_chunk_size" type="int" setter="set_download_chunk_size" getter="get_download_chunk_size" default="65536">
  203. The size of the buffer used and maximum bytes to read per iteration. See [member HTTPClient.read_chunk_size].
  204. 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.
  205. </member>
  206. <member name="download_file" type="String" setter="set_download_file" getter="get_download_file" default="&quot;&quot;">
  207. The file to download into. Will output any received file into it.
  208. </member>
  209. <member name="max_redirects" type="int" setter="set_max_redirects" getter="get_max_redirects" default="8">
  210. Maximum number of allowed redirects.
  211. </member>
  212. <member name="timeout" type="int" setter="set_timeout" getter="get_timeout" default="0">
  213. </member>
  214. <member name="use_threads" type="bool" setter="set_use_threads" getter="is_using_threads" default="false">
  215. If [code]true[/code], multithreading is used to improve performance.
  216. </member>
  217. </members>
  218. <signals>
  219. <signal name="request_completed">
  220. <argument index="0" name="result" type="int" />
  221. <argument index="1" name="response_code" type="int" />
  222. <argument index="2" name="headers" type="PackedStringArray" />
  223. <argument index="3" name="body" type="PackedByteArray" />
  224. <description>
  225. Emitted when a request is completed.
  226. </description>
  227. </signal>
  228. </signals>
  229. <constants>
  230. <constant name="RESULT_SUCCESS" value="0" enum="Result">
  231. Request successful.
  232. </constant>
  233. <constant name="RESULT_CHUNKED_BODY_SIZE_MISMATCH" value="1" enum="Result">
  234. </constant>
  235. <constant name="RESULT_CANT_CONNECT" value="2" enum="Result">
  236. Request failed while connecting.
  237. </constant>
  238. <constant name="RESULT_CANT_RESOLVE" value="3" enum="Result">
  239. Request failed while resolving.
  240. </constant>
  241. <constant name="RESULT_CONNECTION_ERROR" value="4" enum="Result">
  242. Request failed due to connection (read/write) error.
  243. </constant>
  244. <constant name="RESULT_SSL_HANDSHAKE_ERROR" value="5" enum="Result">
  245. Request failed on SSL handshake.
  246. </constant>
  247. <constant name="RESULT_NO_RESPONSE" value="6" enum="Result">
  248. Request does not have a response (yet).
  249. </constant>
  250. <constant name="RESULT_BODY_SIZE_LIMIT_EXCEEDED" value="7" enum="Result">
  251. Request exceeded its maximum size limit, see [member body_size_limit].
  252. </constant>
  253. <constant name="RESULT_BODY_DECOMPRESS_FAILED" value="8" enum="Result">
  254. </constant>
  255. <constant name="RESULT_REQUEST_FAILED" value="9" enum="Result">
  256. Request failed (currently unused).
  257. </constant>
  258. <constant name="RESULT_DOWNLOAD_FILE_CANT_OPEN" value="10" enum="Result">
  259. HTTPRequest couldn't open the download file.
  260. </constant>
  261. <constant name="RESULT_DOWNLOAD_FILE_WRITE_ERROR" value="11" enum="Result">
  262. HTTPRequest couldn't write to the download file.
  263. </constant>
  264. <constant name="RESULT_REDIRECT_LIMIT_REACHED" value="12" enum="Result">
  265. Request reached its maximum redirect limit, see [member max_redirects].
  266. </constant>
  267. <constant name="RESULT_TIMEOUT" value="13" enum="Result">
  268. </constant>
  269. </constants>
  270. </class>