diff --git a/net/http_client.android.ts b/net/http_client.android.ts index d00457dc7..685346eb4 100644 --- a/net/http_client.android.ts +++ b/net/http_client.android.ts @@ -12,18 +12,7 @@ export class http { */ public static getString(url: string): promises.Promise { var d = new promises.Deferred(); - - var context = app_module.tk.ui.Application.current.android.context; - com.koushikdutta.ion.Ion.with(context, url).asString().setCallback(new com.koushikdutta.async.future.FutureCallback({ - onCompleted: function (e, result) { - if (e) { - d.reject(e); - return; - } - d.resolve(result); - } - })); - + http.get(url, r => d.resolve(r), e => d.reject(e)); return d.promise(); } @@ -32,18 +21,7 @@ export class http { */ public static getJSON(url: string): promises.Promise { var d = new promises.Deferred(); - - var context = app_module.tk.ui.Application.current.android.context; - com.koushikdutta.ion.Ion.with(context, url).asString().setCallback(new com.koushikdutta.async.future.FutureCallback({ - onCompleted: function (e, result) { - if (e) { - d.reject(e); - return; - } - d.resolve(JSON.parse(result)); - } - })); - + http.get(url, r => d.resolve(JSON.parse(r)), e => d.reject(e)); return d.promise(); } @@ -52,23 +30,36 @@ export class http { */ public static getImage(url: string): promises.Promise { var d = new promises.Deferred(); - - var context = app_module.tk.ui.Application.current.android.context; - com.koushikdutta.ion.Ion.with(context, url).asBitmap().setCallback(new com.koushikdutta.async.future.FutureCallback({ - onCompleted: function (e, result) { - if (e) { - d.reject(e); - return; - } - - var image = new image_module.Image(); - image.loadFromBitmap(result); - - d.resolve(image); - } - })); - - + http.get(url, r => { + var image = new image_module.Image(); + image.loadFromBitmap(r); + d.resolve(image); + }, e => d.reject(e)); return d.promise(); } + + private static get(url: string, successCallback: (result: any) => void, errorCallback?: (e: Error) => void) { + try { + var isImage = url.match(/\.(jpeg|jpg|gif|png)$/) != null; + + var context = app_module.tk.ui.Application.current.android.context; + var request = com.koushikdutta.ion.Ion.with(context, url); + + request = isImage ? request.asBitmap() : request.asString(); + + request.setCallback(new com.koushikdutta.async.future.FutureCallback({ + onCompleted: function (error, data) { + if (error && errorCallback) { + errorCallback(new Error(error.toString())); + } else if (successCallback) { + successCallback(data); + } + } + })); + } catch (ex) { + if (errorCallback) { + errorCallback(ex); + } + } + } }