android client
[scannr.git] / scannrmobile / src / com / example / scannrmobile / HttpTask.java
blob:a/scannrmobile/src/com/example/scannrmobile/HttpTask.java -> blob:b/scannrmobile/src/com/example/scannrmobile/HttpTask.java
--- a/scannrmobile/src/com/example/scannrmobile/HttpTask.java
+++ b/scannrmobile/src/com/example/scannrmobile/HttpTask.java
@@ -1,1 +1,73 @@
+package com.example.scannrmobile;
 
+import android.os.AsyncTask;
+
+import org.apache.http.client.methods.*;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.impl.client.DefaultHttpClient;
+
+import org.json.*;
+import android.util.Log;
+
+
+//http://www.accella.net/android-http-get-json/
+public class HttpTask extends AsyncTask<HttpUriRequest,Void,JSONArray> {
+    private static final String TAG = "Scannr_HTTP_TASK";
+
+    @Override
+    protected JSONArray doInBackground(HttpUriRequest...params) {
+
+        // Performed on Background Thread
+
+        HttpUriRequest request = params[0];
+        HttpClient client = new DefaultHttpClient();
+
+        try {
+            // The UI Thread shouldn't be blocked long enough to do the reading in of the stream.
+            HttpResponse response =  client.execute(request);
+
+// TODO handle bad response codes (such as 404, etc)
+
+            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
+            StringBuilder builder = new StringBuilder();
+            for (String line = null; (line = reader.readLine()) != null; ) {
+                builder.append(line).append("\n");
+            }
+            JSONTokener tokener = new JSONTokener(builder.toString());
+            JSONArray json = new JSONArray(tokener);
+            return json;
+
+        } catch (Exception e) {
+            // TODO handle different exception cases
+            Log.e(TAG,e.toString());
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    @Override
+    protected void onPostExecute(JSONArray json) {
+        // Done on UI Thread
+        if(json != null) {
+            taskHandler.taskSuccessful(json);
+        } else {
+            taskHandler.taskFailed();
+        }
+    }
+
+    public static interface HttpTaskHandler {
+        void taskSuccessful(JSONArray json);
+        void taskFailed();
+    }
+
+    HttpTaskHandler taskHandler;
+
+    public void setTaskHandler(HttpTaskHandler taskHandler) {
+        this.taskHandler = taskHandler;
+    }
+
+}