HTTPRequest.xml 14 KB

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