app.nit: intro example for AsyncHttpRequest
[nit.git] / lib / app / examples / http_request_example.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Example for the `app::http_request` main service `AsyncHttpRequest`
16 module http_request_example
17
18 import app::ui
19 import app::http_request
20
21 # Simple asynchronous HTTP request to http://example.com/ displaying feedback to the window
22 class MyHttpRequest
23 super AsyncHttpRequest
24
25 # Back reference to the window to show feedback to the user
26 var win: HttpRequestClientWindow
27
28 # ---
29 # Config the request
30
31 redef fun uri do return "http://example.com/"
32 redef fun deserialize_json do return false
33
34 # ---
35 # Customize callbacks
36
37 redef fun before
38 do
39 win.label_response.text = "Sending request..."
40
41 # Disable button to prevent double requests
42 win.button_request.enabled = false
43 end
44
45 redef fun on_load(data, status)
46 do win.label_response.text = "Received response code {status} with {data.as(Text).byte_length} bytes"
47
48 redef fun on_fail(error)
49 do win.label_response.text = "Connection error: {error}"
50
51 redef fun after do win.button_request.enabled = true
52 end
53
54 # Simpe window with a label and a button
55 class HttpRequestClientWindow
56 super Window
57
58 # Root layout
59 var layout = new VerticalLayout(parent=self)
60
61 # Button to send request
62 var button_request = new Button(parent=layout, text="Press to send HTTP request")
63
64 # Label displaying feedback to user
65 var label_response = new Label(parent=layout, text="No response yet.")
66
67 init do button_request.observers.add self
68
69 redef fun on_event(event)
70 do
71 if event isa ButtonPressEvent and event.sender == button_request then
72 # Prepare and send request
73 var request = new MyHttpRequest(self)
74 request.start
75 end
76 end
77 end
78
79 redef class App
80 redef fun on_create
81 do
82 # Create the main window
83 push_window new HttpRequestClientWindow
84 super
85 end
86 end