class_httprequest.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. :github_url: hide
  2. .. Generated automatically by doc/tools/makerst.py in Godot's source tree.
  3. .. DO NOT EDIT THIS FILE, but the HTTPRequest.xml source instead.
  4. .. The source is found in doc/classes or modules/<name>/doc_classes.
  5. .. _class_HTTPRequest:
  6. HTTPRequest
  7. ===========
  8. **Inherits:** :ref:`Node<class_Node>` **<** :ref:`Object<class_Object>`
  9. A node with the ability to send HTTP(S) requests.
  10. Description
  11. -----------
  12. A node with the ability to send HTTP requests. Uses :ref:`HTTPClient<class_HTTPClient>` internally.
  13. Can be used to make HTTP requests, i.e. download or upload files or web content via HTTP.
  14. **Example of contacting a REST API and printing one of its returned fields:**
  15. ::
  16. func _ready():
  17. # Create an HTTP request node and connect its completion signal.
  18. var http_request = HTTPRequest.new()
  19. add_child(http_request)
  20. http_request.connect("request_completed", self, "_http_request_completed")
  21. # Perform a GET request. The URL below returns JSON as of writing.
  22. var error = http_request.request("https://httpbin.org/get")
  23. if error != OK:
  24. push_error("An error occurred in the HTTP request.")
  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 = {"name": "Godette"}
  29. error = http_request.request("https://httpbin.org/post", [], true, HTTPClient.METHOD_POST, body)
  30. if error != OK:
  31. push_error("An error occurred in the HTTP request.")
  32. # Called when the HTTP request is completed.
  33. func _http_request_completed(result, response_code, headers, body):
  34. var response = parse_json(body.get_string_from_utf8())
  35. # Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
  36. print(response.headers["User-Agent"])
  37. **Example of loading and displaying an image using HTTPRequest:**
  38. ::
  39. func _ready():
  40. # Create an HTTP request node and connect its completion signal.
  41. var http_request = HTTPRequest.new()
  42. add_child(http_request)
  43. http_request.connect("request_completed", self, "_http_request_completed")
  44. # Perform the HTTP request. The URL below returns a PNG image as of writing.
  45. var error = http_request.request("https://via.placeholder.com/512")
  46. if error != OK:
  47. push_error("An error occurred in the HTTP request.")
  48. # Called when the HTTP request is completed.
  49. func _http_request_completed(result, response_code, headers, body):
  50. var image = Image.new()
  51. var error = image.load_png_from_buffer(body)
  52. if error != OK:
  53. push_error("Couldn't load the image.")
  54. var texture = ImageTexture.new()
  55. texture.create_from_image(image)
  56. # Display the image in a TextureRect node.
  57. var texture_rect = TextureRect.new()
  58. add_child(texture_rect)
  59. texture_rect.texture = texture
  60. **Note:** When performing HTTP requests from a project exported to HTML5, keep in mind the remote server may not allow requests from foreign origins due to `CORS <https://developer.mozilla.org/en-US/docs/Web/HTTP/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.
  61. **Note:** SSL/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.
  62. Tutorials
  63. ---------
  64. - :doc:`../tutorials/networking/http_request_class`
  65. - :doc:`../tutorials/networking/ssl_certificates`
  66. Properties
  67. ----------
  68. +-----------------------------+----------------------------------------------------------------------------+-----------+
  69. | :ref:`int<class_int>` | :ref:`body_size_limit<class_HTTPRequest_property_body_size_limit>` | ``-1`` |
  70. +-----------------------------+----------------------------------------------------------------------------+-----------+
  71. | :ref:`int<class_int>` | :ref:`download_chunk_size<class_HTTPRequest_property_download_chunk_size>` | ``65536`` |
  72. +-----------------------------+----------------------------------------------------------------------------+-----------+
  73. | :ref:`String<class_String>` | :ref:`download_file<class_HTTPRequest_property_download_file>` | ``""`` |
  74. +-----------------------------+----------------------------------------------------------------------------+-----------+
  75. | :ref:`int<class_int>` | :ref:`max_redirects<class_HTTPRequest_property_max_redirects>` | ``8`` |
  76. +-----------------------------+----------------------------------------------------------------------------+-----------+
  77. | :ref:`int<class_int>` | :ref:`timeout<class_HTTPRequest_property_timeout>` | ``0`` |
  78. +-----------------------------+----------------------------------------------------------------------------+-----------+
  79. | :ref:`bool<class_bool>` | :ref:`use_threads<class_HTTPRequest_property_use_threads>` | ``false`` |
  80. +-----------------------------+----------------------------------------------------------------------------+-----------+
  81. Methods
  82. -------
  83. +---------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  84. | void | :ref:`cancel_request<class_HTTPRequest_method_cancel_request>` **(** **)** |
  85. +---------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  86. | :ref:`int<class_int>` | :ref:`get_body_size<class_HTTPRequest_method_get_body_size>` **(** **)** |const| |
  87. +---------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  88. | :ref:`int<class_int>` | :ref:`get_downloaded_bytes<class_HTTPRequest_method_get_downloaded_bytes>` **(** **)** |const| |
  89. +---------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  90. | :ref:`Status<enum_HTTPClient_Status>` | :ref:`get_http_client_status<class_HTTPRequest_method_get_http_client_status>` **(** **)** |const| |
  91. +---------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  92. | :ref:`Error<enum_@GlobalScope_Error>` | :ref:`request<class_HTTPRequest_method_request>` **(** :ref:`String<class_String>` url, :ref:`PoolStringArray<class_PoolStringArray>` custom_headers=PoolStringArray( ), :ref:`bool<class_bool>` ssl_validate_domain=true, :ref:`Method<enum_HTTPClient_Method>` method=0, :ref:`String<class_String>` request_data="" **)** |
  93. +---------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  94. Signals
  95. -------
  96. .. _class_HTTPRequest_signal_request_completed:
  97. - **request_completed** **(** :ref:`int<class_int>` result, :ref:`int<class_int>` response_code, :ref:`PoolStringArray<class_PoolStringArray>` headers, :ref:`PoolByteArray<class_PoolByteArray>` body **)**
  98. Emitted when a request is completed.
  99. Enumerations
  100. ------------
  101. .. _enum_HTTPRequest_Result:
  102. .. _class_HTTPRequest_constant_RESULT_SUCCESS:
  103. .. _class_HTTPRequest_constant_RESULT_CHUNKED_BODY_SIZE_MISMATCH:
  104. .. _class_HTTPRequest_constant_RESULT_CANT_CONNECT:
  105. .. _class_HTTPRequest_constant_RESULT_CANT_RESOLVE:
  106. .. _class_HTTPRequest_constant_RESULT_CONNECTION_ERROR:
  107. .. _class_HTTPRequest_constant_RESULT_SSL_HANDSHAKE_ERROR:
  108. .. _class_HTTPRequest_constant_RESULT_NO_RESPONSE:
  109. .. _class_HTTPRequest_constant_RESULT_BODY_SIZE_LIMIT_EXCEEDED:
  110. .. _class_HTTPRequest_constant_RESULT_REQUEST_FAILED:
  111. .. _class_HTTPRequest_constant_RESULT_DOWNLOAD_FILE_CANT_OPEN:
  112. .. _class_HTTPRequest_constant_RESULT_DOWNLOAD_FILE_WRITE_ERROR:
  113. .. _class_HTTPRequest_constant_RESULT_REDIRECT_LIMIT_REACHED:
  114. .. _class_HTTPRequest_constant_RESULT_TIMEOUT:
  115. enum **Result**:
  116. - **RESULT_SUCCESS** = **0** --- Request successful.
  117. - **RESULT_CHUNKED_BODY_SIZE_MISMATCH** = **1**
  118. - **RESULT_CANT_CONNECT** = **2** --- Request failed while connecting.
  119. - **RESULT_CANT_RESOLVE** = **3** --- Request failed while resolving.
  120. - **RESULT_CONNECTION_ERROR** = **4** --- Request failed due to connection (read/write) error.
  121. - **RESULT_SSL_HANDSHAKE_ERROR** = **5** --- Request failed on SSL handshake.
  122. - **RESULT_NO_RESPONSE** = **6** --- Request does not have a response (yet).
  123. - **RESULT_BODY_SIZE_LIMIT_EXCEEDED** = **7** --- Request exceeded its maximum size limit, see :ref:`body_size_limit<class_HTTPRequest_property_body_size_limit>`.
  124. - **RESULT_REQUEST_FAILED** = **8** --- Request failed (currently unused).
  125. - **RESULT_DOWNLOAD_FILE_CANT_OPEN** = **9** --- HTTPRequest couldn't open the download file.
  126. - **RESULT_DOWNLOAD_FILE_WRITE_ERROR** = **10** --- HTTPRequest couldn't write to the download file.
  127. - **RESULT_REDIRECT_LIMIT_REACHED** = **11** --- Request reached its maximum redirect limit, see :ref:`max_redirects<class_HTTPRequest_property_max_redirects>`.
  128. - **RESULT_TIMEOUT** = **12**
  129. Property Descriptions
  130. ---------------------
  131. .. _class_HTTPRequest_property_body_size_limit:
  132. - :ref:`int<class_int>` **body_size_limit**
  133. +-----------+----------------------------+
  134. | *Default* | ``-1`` |
  135. +-----------+----------------------------+
  136. | *Setter* | set_body_size_limit(value) |
  137. +-----------+----------------------------+
  138. | *Getter* | get_body_size_limit() |
  139. +-----------+----------------------------+
  140. Maximum allowed size for response bodies.
  141. ----
  142. .. _class_HTTPRequest_property_download_chunk_size:
  143. - :ref:`int<class_int>` **download_chunk_size**
  144. +-----------+--------------------------------+
  145. | *Default* | ``65536`` |
  146. +-----------+--------------------------------+
  147. | *Setter* | set_download_chunk_size(value) |
  148. +-----------+--------------------------------+
  149. | *Getter* | get_download_chunk_size() |
  150. +-----------+--------------------------------+
  151. The size of the buffer used and maximum bytes to read per iteration. See :ref:`HTTPClient.read_chunk_size<class_HTTPClient_property_read_chunk_size>`.
  152. 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.
  153. ----
  154. .. _class_HTTPRequest_property_download_file:
  155. - :ref:`String<class_String>` **download_file**
  156. +-----------+--------------------------+
  157. | *Default* | ``""`` |
  158. +-----------+--------------------------+
  159. | *Setter* | set_download_file(value) |
  160. +-----------+--------------------------+
  161. | *Getter* | get_download_file() |
  162. +-----------+--------------------------+
  163. The file to download into. Will output any received file into it.
  164. ----
  165. .. _class_HTTPRequest_property_max_redirects:
  166. - :ref:`int<class_int>` **max_redirects**
  167. +-----------+--------------------------+
  168. | *Default* | ``8`` |
  169. +-----------+--------------------------+
  170. | *Setter* | set_max_redirects(value) |
  171. +-----------+--------------------------+
  172. | *Getter* | get_max_redirects() |
  173. +-----------+--------------------------+
  174. Maximum number of allowed redirects.
  175. ----
  176. .. _class_HTTPRequest_property_timeout:
  177. - :ref:`int<class_int>` **timeout**
  178. +-----------+--------------------+
  179. | *Default* | ``0`` |
  180. +-----------+--------------------+
  181. | *Setter* | set_timeout(value) |
  182. +-----------+--------------------+
  183. | *Getter* | get_timeout() |
  184. +-----------+--------------------+
  185. ----
  186. .. _class_HTTPRequest_property_use_threads:
  187. - :ref:`bool<class_bool>` **use_threads**
  188. +-----------+------------------------+
  189. | *Default* | ``false`` |
  190. +-----------+------------------------+
  191. | *Setter* | set_use_threads(value) |
  192. +-----------+------------------------+
  193. | *Getter* | is_using_threads() |
  194. +-----------+------------------------+
  195. If ``true``, multithreading is used to improve performance.
  196. Method Descriptions
  197. -------------------
  198. .. _class_HTTPRequest_method_cancel_request:
  199. - void **cancel_request** **(** **)**
  200. Cancels the current request.
  201. ----
  202. .. _class_HTTPRequest_method_get_body_size:
  203. - :ref:`int<class_int>` **get_body_size** **(** **)** |const|
  204. Returns the response body length.
  205. **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``.
  206. ----
  207. .. _class_HTTPRequest_method_get_downloaded_bytes:
  208. - :ref:`int<class_int>` **get_downloaded_bytes** **(** **)** |const|
  209. Returns the amount of bytes this HTTPRequest downloaded.
  210. ----
  211. .. _class_HTTPRequest_method_get_http_client_status:
  212. - :ref:`Status<enum_HTTPClient_Status>` **get_http_client_status** **(** **)** |const|
  213. Returns the current status of the underlying :ref:`HTTPClient<class_HTTPClient>`. See :ref:`Status<enum_HTTPClient_Status>`.
  214. ----
  215. .. _class_HTTPRequest_method_request:
  216. - :ref:`Error<enum_@GlobalScope_Error>` **request** **(** :ref:`String<class_String>` url, :ref:`PoolStringArray<class_PoolStringArray>` custom_headers=PoolStringArray( ), :ref:`bool<class_bool>` ssl_validate_domain=true, :ref:`Method<enum_HTTPClient_Method>` method=0, :ref:`String<class_String>` request_data="" **)**
  217. Creates request on the underlying :ref:`HTTPClient<class_HTTPClient>`. If there is no configuration errors, it tries to connect using :ref:`HTTPClient.connect_to_host<class_HTTPClient_method_connect_to_host>` and passes parameters onto :ref:`HTTPClient.request<class_HTTPClient_method_request>`.
  218. Returns :ref:`@GlobalScope.OK<class_@GlobalScope_constant_OK>` if request is successfully created. (Does not imply that the server has responded), :ref:`@GlobalScope.ERR_UNCONFIGURED<class_@GlobalScope_constant_ERR_UNCONFIGURED>` if not in the tree, :ref:`@GlobalScope.ERR_BUSY<class_@GlobalScope_constant_ERR_BUSY>` if still processing previous request, :ref:`@GlobalScope.ERR_INVALID_PARAMETER<class_@GlobalScope_constant_ERR_INVALID_PARAMETER>` if given string is not a valid URL format, or :ref:`@GlobalScope.ERR_CANT_CONNECT<class_@GlobalScope_constant_ERR_CANT_CONNECT>` if not using thread and the :ref:`HTTPClient<class_HTTPClient>` cannot connect to host.
  219. **Note:** The ``request_data`` parameter is ignored if ``method`` is :ref:`HTTPClient.METHOD_GET<class_HTTPClient_constant_METHOD_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 :ref:`String.http_escape<class_String_method_http_escape>` for an example.
  220. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)`
  221. .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`
  222. .. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`