Skip to content

Commit 9ec0130

Browse files
authored
Added documentation covering http path, streaming and proxies (#620)
* Update http-requests.md * Review fixes
1 parent 238bb0b commit 9ec0130

1 file changed

Lines changed: 128 additions & 6 deletions

File tree

docs/en/manuals/http-requests.md

Lines changed: 128 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@ Defold can make normal HTTP requests using the `http.request()` function.
1111

1212
This is the most basic request to get some data from the server. Example:
1313

14-
```Lua
14+
```lua
1515
local function handle_response(self, id, response)
1616
print(response.status, response.response)
1717
end
1818

1919
http.request("https://www.defold.com", "GET", handle_response)
2020
```
2121

22-
This will make an HTTP GET request to https://www.defold.com. The function is asynchronous and will not block while making the request. Once the request has been made and a server has sent a response it will invoke/call the provided callback function. The callback function will receive the full server response, including status code and response headers.
22+
This will make an HTTP GET request to https://www.defold.com. The function is asynchronous and will not block while making the request. Once the request has been made and a server has sent a response it will invoke/call the provided callback function. The callback function will receive the full server response, including status code and response headers. See below for additional information about how to work with the response table.
2323

2424
::: sidenote
2525
HTTP requests are automatically cached in the client to improve network performance. The cached files are stored in an OS specific application support path in a folder named `defold/http-cache`. You usually don't have to care about the HTTP cache but if you need to clear the cache during development you can manually delete the folder containing the cached files. On macOS this folder is located in `%HOME%/Library/Application Support/Defold/http-cache/` and on Windows in `%APP_DATA%/defold/http-cache`.
@@ -29,21 +29,143 @@ HTTP requests are automatically cached in the client to improve network performa
2929

3030
When sending data, like a score or some authentication data, to a server it is typically done using a POST requests:
3131

32+
```lua
33+
local function handle_response(self, id, response)
34+
print(response.status, response.response)
35+
end
36+
37+
local body = "12345"
38+
http.request("https://www.myserver.com/score", "POST", handle_response, nil, body)
39+
```
40+
41+
42+
### Other HTTP methods
43+
44+
Defold HTTP requests also support the HEAD, DELETE and PUT methods. The CONNECT method is also supported (see section about proxy connections below).
45+
46+
### How to work with the HTTP response
47+
48+
The `response` table returned in the callback contains all of the information necessary to implement granular reponse handling. Two of the key fields are `status` and `response`:
49+
50+
```lua
51+
52+
local function handle_response(self, id, response)
53+
-- check the response status code. Common response codes:
54+
-- 200 OK - the request completed successfully
55+
-- 301 Moved permanently - the requested data has moved, see redirect header
56+
-- 307 Temporary redirect - same as above
57+
-- 208 Permanent redirect - same as above
58+
-- 400 Bad Request - the request was malformed
59+
-- 401 Unauthorized - the client must authenticate itself
60+
-- 404 Not Found - the server cannot find the information
61+
-- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status
62+
if response.status == 200 then
63+
-- the response data
64+
-- this can be anything from plain text, json encoded data or binary data
65+
print(response.response)
66+
json.decode(response.response)
67+
sys.save(..., response.response)
68+
end
69+
end
70+
```
71+
72+
When the response contains a large blob of binary data such as an image or a music track it might make sense to write the data to a file instead of loading it into memory:
73+
74+
```lua
75+
-- in this example we download myimage.png and write it directly to a file on disk
76+
77+
local options = {
78+
path = sys.get_save_file("mygame", "myimage.png")
79+
}
80+
81+
local function handle_response(self, id, response)
82+
if response.status == 200 then
83+
print("File was successfully written to:", response.path)
84+
print("File size:", response.document_size)
85+
print("File path:", response.path)
86+
else
87+
print("File was not written to disk:", response.error)
88+
end
89+
end
90+
91+
http.request("https://www.foobar.com/myimage.png", "GET", handle_response)
92+
```
93+
94+
Another use-case for loading large amounts of data over the network is sound streaming, when "chunks" of sound data are loaded from a URL and fed into a sound resource. A complete example can be found in the [Sound Streaming manual](/sound-streaming#sound-streaming).
95+
96+
97+
### Request headers
98+
99+
It is possible to set additional headers when sending a request. This can for instance be used to set an authorization header or content type to tell the server which format the
100+
32101
```Lua
33102
local function handle_response(self, id, response)
34103
print(response.status, response.response)
35104
end
36105

106+
-- send some form data
37107
local headers = {
38108
["Content-Type"] = "application/x-www-form-urlencoded"
39109
}
40-
local body = "foo=bar"
41-
http.request("https://httpbin.org/post", "POST", handle_response, headers, body)
110+
local body = "key1=value1&key2=value2"
111+
http.request("https://www.myserver.com/post", "POST", handle_response, headers, body)
112+
113+
-- send some json encoded data
114+
local headers = {
115+
["Content-Type"] = "application/json"
116+
}
117+
local body = json.encode({ key1 = value1, key2 = value2 })
118+
http.request("https://www.myserver.com/post", "POST", handle_response, headers, body)
119+
120+
-- request some data which requires authorization to access
121+
local token = ... -- generate an access token (JWT, OAuth etc)
122+
local headers = {
123+
["Authorization"] = "Bearer " .. token
124+
}
125+
http.request("https://www.myserver.com/content", "GET", handle_response, headers)
42126
```
43127

44-
### Other HTTP methods
128+
Defold will automatically set a couple of request headers:
129+
130+
* `If-None-Match: <etag>` will be set with the ETag of any previously cached response.
131+
* `Transfer-Encoding: chunked` will be set if the request body is larger than 16384 bytes.
132+
* `Content-Length` will be set with the size of the request body (unless the request is chunked).
133+
* `Range: bytes=<from>-<to>` will be set if requesting a partial response, for instance when [streaming sounds](/sound-streaming#sound-streaming).
134+
135+
136+
### Response headers
45137

46-
Defold HTTP requests also support the HEAD, DELETE and PUT methods.
138+
The server response may contain one or more response headers. These are available on the `response` table:
139+
140+
```lua
141+
local function handle_response(self, id, response)
142+
for header,value in pairs(response.headers) do
143+
print(header, value)
144+
end
145+
end
146+
147+
http.request("https://www.defold.com", "GET", handle_response)
148+
```
149+
150+
151+
### HTTP Proxy
152+
153+
It is sometimes desirable to send a request through a proxy server. This can be done by specifying a proxy server to use when connecting to the destination server. When a proxy is used the connection to the destination server is established using an a HTTP tunnel through the proxy. The HTTP tunnel is established using the CONNECT HTTP method. Example:
154+
155+
156+
```lua
157+
-- connect to www.defold.com via localhost proxy on port 8888
158+
local url = "https://www.defold.com:443"
159+
local method = "GET"
160+
local headers = {}
161+
local post_data = nil
162+
local options = {
163+
proxy = "https://127.0.0.1:8888"
164+
}
165+
http.request(url, method, function(self, id, response)
166+
pprint(response)
167+
end, headers, post_data, options)
168+
```
47169

48170
### API Reference
49171

0 commit comments

Comments
 (0)