Making HTTP requests¶
For the sake of this example, we will create a simple UI with a button, that when pressed will start the HTTP request to the specified URL.
Create a new empty scene, add a CanvasLayer as the root node and add a script to it. Then add two child nodes to it: a Button and an HTTPRequest node. You will need to connect the following signals to the CanvasLayer script:
Button.pressed: When the button is pressed, we will start the request.
HTTPRequest.request_completed: When the request is completed, we will get the requested data as an argument.
Below is all the code we need to make it work. The URL points to an online API mocker; it returns a pre-defined JSON string, which we will then parse to get access to the data.
With this, you should see
(hello:world) printed on the console; hello being a key, and world being a value, both of them strings.
Note that you may want to check whether the
RESULT_SUCCESS and whether a JSON parsing error occurred, see the JSON class reference and HTTPRequest for more.
Of course, you can also set custom HTTP headers. These are given as a string array, with each string containing a header in the format
For example, to set a custom user agent (the HTTP
user-agent header) you could use the following:
Please note that, for SSL/TLS encryption and thus HTTPS URLs to work, you may need to take some steps as described here.
Also, when calling APIs using authorization, be aware that someone might analyse and decompile your released application and thus may gain access to any embedded authorization information like tokens, usernames or passwords. That means it is usually not a good idea to embed things such as database access credentials inside your game. Avoid providing information useful to an attacker whenever possible.
Sending data to server¶
Until now, we have limited ourselves to requesting data from a server. But what if you need to send data to the server? Here is a common way of doing it:
Keep in mind that you have to wait for a request to finish before sending another one. Making multiple request at once requires you to have one node per request. A common strategy is to create and delete HTTPRequest nodes at runtime as necessary.