package uk.co.blatech.blaupload.util; import android.os.AsyncTask; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BasicClientCookie; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * This class is used for loading a JSON array from a given URL * * TODO: Make the cookie stuff generic * Created by joe on 02/08/14. */ public class JSONLoader extends AsyncTask { private String url; /** * * @param url - The URL to load JSON from * @return JSONArray of data from the URL */ @Override protected JSONArray doInBackground(String... url) { this.url = url[0]; String jsonText = readJSON(); JSONArray json = null; try { json = new JSONArray(jsonText); } catch (JSONException e) { //TODO: Error handling if we got something other than JSON Log.e(JSONLoader.class.toString(), "Failed to parse JSON"); e.printStackTrace(); } return json; } private String readJSON() { StringBuilder builder = new StringBuilder(); DefaultHttpClient client = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); //TODO: Don't hard code the cookie. BasicClientCookie cookie = new BasicClientCookie("password", "lolnopass"); cookie.setDomain(".blaupload.co.uk"); cookie.setPath("/"); cookieStore.addCookie(cookie); client.setCookieStore(cookieStore); HttpGet httpGet = new HttpGet(url); try { //Read the JSON from the URL HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { //TODO: Error handling if there's no JSON there Log.e(JSONLoader.class.toString(), "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } @Override protected void onPostExecute(JSONArray result) { EventBus.getInstance().post(new JSONLoaderResultEvent(result)); } }