3c614982bf4b13d935635cfa77f4eb1f6ed4fbb9
[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 is
17 app_name "app.nit HTTP"
18 app_namespace "org.nitlanguage.http_example"
19 android_api_target 15
20 end
21
22 import app::ui
23 import app::http_request
24 import android::aware # for android_api_target
25
26 # Simple asynchronous HTTP request to http://example.com/ displaying feedback to the window
27 class MyHttpRequest
28 super AsyncHttpRequest
29
30 # Back reference to the window to show feedback to the user
31 var win: HttpRequestClientWindow
32
33 # ---
34 # Config the request
35
36 redef fun uri do return "http://example.com/"
37 redef fun deserialize_json do return false
38
39 # ---
40 # Customize callbacks
41
42 redef fun before
43 do
44 win.label_response.text = "Sending request..."
45
46 # Disable button to prevent double requests
47 win.button_request.enabled = false
48 end
49
50 redef fun on_load(data, status)
51 do win.label_response.text = "Received response code {status} with {data.as(Text).byte_length} bytes"
52
53 redef fun on_fail(error)
54 do win.label_response.text = "Connection error: {error}"
55
56 redef fun after do win.button_request.enabled = true
57 end
58
59 # Simple window with a label and a button
60 class HttpRequestClientWindow
61 super Window
62
63 # Root layout
64 var layout = new ListLayout(parent=self)
65
66 # Button to send request
67 var button_request = new Button(parent=layout, text="Press to send HTTP request")
68
69 # Label displaying feedback to user
70 var label_response = new Label(parent=layout, text="No response yet.")
71
72 init do button_request.observers.add self
73
74 redef fun on_event(event)
75 do
76 if event isa ButtonPressEvent and event.sender == button_request then
77 # Prepare and send request
78 var request = new MyHttpRequest(self)
79 request.start
80 end
81 end
82 end
83
84 redef fun root_window do return new HttpRequestClientWindow