1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Android implementation of `app:http_request`
16 module http_request
is
17 android_manifest
"""<uses-permission android:name="android.permission.INTERNET" />"""
20 intrude import app
::http_request
24 import org.apache.http.client.methods.HttpGet;
25 import org.apache.http.impl.client.DefaultHttpClient;
26 import org.apache.http.HttpResponse;
27 import org.apache.http.HttpStatus;
28 import org.apache.http.StatusLine;
29 import java.io.ByteArrayOutputStream;
33 redef fun run_on_ui_thread
(task
)
35 if app
.activities
.not_empty
then
36 app
.native_activity
.run_on_ui_thread task
38 # There is no UI, it must be a service, run on the caller thread
48 jni_env
.push_local_frame
8
49 var juri
= self.to_java_string
50 var jrep
= java_http_get
(juri
)
52 assert not jrep
.is_java_null
55 if jrep
.is_exception
then
56 jrep
= jrep
.as_exception
57 res
= new HttpRequestResult(null, new IOError(jrep
.message
.to_s
))
58 else if jrep
.is_http_response
then
59 jrep
= jrep
.as_http_response
60 res
= new HttpRequestResult(jrep
.content
.to_s
, null, jrep
.status_code
)
63 jni_env
.pop_local_frame
68 redef class AsyncHttpRequest
73 jvm
.detach_current_thread
78 redef class JavaObject
79 private fun is_exception
: Bool in "Java" `{ return self instanceof Exception; `}
80 private fun as_exception: JavaException in "Java" `{ return (Exception)self; `}
82 private fun is_http_response
: Bool in "Java" `{ return self instanceof HttpResponse; `}
83 private fun as_http_response: JavaHttpResponse in "Java" `{ return (HttpResponse)self; `}
86 private fun java_http_get
(uri
: JavaString): JavaObject in "Java" `{
88 DefaultHttpClient client = new DefaultHttpClient();
89 HttpGet get = new HttpGet(uri);
90 return client.execute(get);
91 } catch (Exception ex) {
96 private extern class JavaHttpResponse in "Java" `{ org.apache.http.HttpResponse `}
99 fun status_code: Int in "Java" `{ return self.getStatusLine().getStatusCode(); `}
101 fun content
: JavaString in "Java" `{
103 ByteArrayOutputStream out = new ByteArrayOutputStream();
104 self.getEntity().writeTo(out);
106 return out.toString();
107 } catch (Exception ex) {
108 ex.printStackTrace();
114 # Force linearization of print
116 # TODO prioritize `android::log`
117 redef fun print
(object
) do super