Back to project page Joetz-Android-V2.
The source code is released under:
GNU General Public License
If you think the Android project Joetz-Android-V2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.example.jens.myapplication.apimanager; /*from w w w . j a v a 2s.com*/ import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.util.Log; import com.example.jens.myapplication.apimanager.manager.ImageManager; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.UnknownHostException; /** * Class for handling requests to the backend */ public class ApiConnection { /** * Indicates the server could not be reached. */ public static final int STATUS_UNKNOWN_HOST = -1; public static final int STATUS_CONNECTION_EXCEPTION = -2; public static final int STATUS_OTHER = Integer.MIN_VALUE; public static final int STATUS_OK = 200; public static final int STATUS_OK_NO_BODY = 204; public static final int STATUS_BAD_REQUEST = 400; public static final int STATUS_UNAUTHORIZED = 401; public static final int STATUS_CONFLICT = 409; public static final int STATUS_INTERNAL_SERVER_ERROR = 500; public static final int REQUEST_GET = 0; public static final int REQUEST_POST = 1; public static final int REQUEST_PUT = 2; public static final int REQUEST_DELETE = 3; //MOCK SERVER //private static final String URL = "http://private-anon-a7172db42-joetz.apiary-mock.com/"; //REAL SERVER public static final String URL = "http://joetzdev.azurewebsites.net/"; private static final String STANDARD_CONTENT_TYPE = "application/json"; /** * Sends a POST request to the Joetz server. * @param action (www.example.com/{action}) [e.g. api/camps] * @param jsonTask Function that parses the JSON code and returns an object. * @param postTask Object holding a procedure to be executed AFTER the request and json parsing * has completed. * (Executed on main thread, possible to do UI adjustment here) * @param requestParams Parameters for the request */ public static <T> CancellableTask post(String action, JSONParsingTask<T> jsonTask, PostRequestTask<T> postTask, RequestParams requestParams){ HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_POST, jsonTask, postTask, requestParams); task.execute(); return task; } /** * Sends a GET request to the Joetz server. * @param action (www.example.com/{action}) [e.g. api/camps] * @param jsonTask Function that parses the JSON code and returns an object. * @param postTask Object holding a procedure to be executed AFTER the request and json parsing * has completed. * (Executed on main thread, possible to do UI adjustment here) * @param requestParams Parameters for the request */ public static <T> CancellableTask get(String action, JSONParsingTask<T> jsonTask, PostRequestTask<T> postTask, RequestParams requestParams){ //new HttpGetAsyncTask(action, postTask, authToken).execute(); HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_GET, jsonTask, postTask, requestParams); task.execute(); return task; } /** * Sends a PUT request to the Joetz server. * @param action (www.example.com/{action}) [e.g. api/camps] * @param jsonTask Function that parses the JSON code and returns an object. * @param postTask Object holding a procedure to be executed AFTER the request and json parsing * has completed. * (Executed on main thread, possible to do UI adjustment here) * @param requestParams Parameters for the request */ public static <T> CancellableTask put(String action, JSONParsingTask<T> jsonTask, PostRequestTask<T> postTask, RequestParams requestParams){ HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_PUT, jsonTask, postTask, requestParams); task.execute(); return task; } /** * Sends a DELETE request to the Joetz server. * @param action (www.example.com/{action}) [e.g. api/users/people/{id}] * @param jsonTask Function that parses the JSON code and returns an object. * @param postTask Object holding a procedure to be executed AFTER the request and json parsing * has completed. * (Executed on main thread, possible to do UI adjustment here) * @param requestParams Parameters for the request */ public static <T> CancellableTask delete(String action, JSONParsingTask<T> jsonTask, PostRequestTask<T> postTask, RequestParams requestParams){ HttpAsyncTask<T> task = new HttpAsyncTask<T>(action, REQUEST_DELETE, jsonTask, postTask, requestParams); task.execute(); return task; } @Deprecated public static CancellableTask getImage(String action, ImageManager.OnImageLoadedListener callback){ ImageLoadingAsyncTask task = new ImageLoadingAsyncTask(action, callback); task.execute(); return task; } /** * Converts the inputstream into a String. * @param inputStream Input stream returned by the HttpResponse * @return JSON String * @throws java.io.IOException */ private static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null){ result += line; } inputStream.close(); return result; } public static boolean isSuccessCode(int statusCode){ return statusCode >= 200 && statusCode < 300; } public static boolean isConnectionFailedCode(int statusCode){ return statusCode < 0; } /** * AsyncTask to handle API requests */ private static class HttpAsyncTask<T> extends AsyncTask<Void, Void, T> implements CancellableTask{ private String action; private int requestType; private JSONParsingTask<T> jsonTask; private PostRequestTask<T> postTask; private RequestParams requestParams; private volatile boolean wasCancelled = false; private volatile int statusCode; /** * Executes the request to the server * @param action (www.example.com/api/{action}) * //@param jsonObject JSON Object containing required data to post. [optional (null)] * @param jsonTask Task that will parse the JSON and return an object. * @param postTask Task that will be executed AFTER the request and the JSON parsing * are finished. * @param requestParams Parameters for the request */ public HttpAsyncTask(String action, int requestType, JSONParsingTask<T> jsonTask, PostRequestTask<T> postTask, RequestParams requestParams){ super(); this.action = action; this.requestType = requestType; this.jsonTask = jsonTask; this.postTask = postTask; this.requestParams = requestParams == null ? new RequestParams() : requestParams; } @Override protected T doInBackground(Void... params) { try { //testing purposes waiting time /*try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); }*/ HttpRequestBase requestBase = null; String fullUrl = URL + action; if(requestType == REQUEST_POST || requestType == REQUEST_PUT){ HttpEntityEnclosingRequestBase httpBase; switch(requestType){ case REQUEST_POST: httpBase = new HttpPost(fullUrl); break; case REQUEST_PUT: httpBase = new HttpPut(fullUrl); break; default: Log.wtf("ApiConnection", "something else in post/put"); return null; } if(requestParams.getRawBody() != null){ httpBase.setEntity(requestParams.getRawBody()); } if(requestParams.getContentType() == null){ httpBase.setHeader("Content-type", STANDARD_CONTENT_TYPE); }else{ httpBase.setHeader("Content-Type", requestParams.getContentType()); } requestBase = httpBase; }else if(requestType == REQUEST_GET) { requestBase = new HttpGet(fullUrl); }else if(requestType == REQUEST_DELETE){ requestBase = new HttpDelete(fullUrl); }else{ statusCode = STATUS_OTHER; return null; } if(requestParams.getAcceptHeader() != null){ requestBase.setHeader("Accept", requestParams.getAcceptHeader()); } if(requestParams.getAuthKey() != null){ requestBase.setHeader("Authorization", requestParams.getAuthKey()); } HttpResponse response = executeRequest(requestBase); if(wasCancelled){ return null; } statusCode = response.getStatusLine().getStatusCode(); Log.d("ApiConnection", "Statuscode: " + statusCode); String pureJson = null; if(response.getEntity() != null){ InputStream inputStream = response.getEntity().getContent(); pureJson = convertInputStreamToString(inputStream); Log.d("ApiConnection", "JSON: " + pureJson); } if(wasCancelled){ return null; } if(statusCode != STATUS_OK || jsonTask == null){ return null; } try{ return jsonTask.handleJSON(pureJson); }catch(IOException e){ e.printStackTrace(); return null; } }catch(UnknownHostException e){ statusCode = ApiConnection.STATUS_UNKNOWN_HOST; return null; }catch(HttpHostConnectException e){ statusCode = ApiConnection.STATUS_CONNECTION_EXCEPTION; return null; } catch (IOException e) { e.printStackTrace(); statusCode = STATUS_OTHER; return null; } } private HttpResponse executeRequest(HttpRequestBase requestBase) throws IOException { HttpClient httpClient = new DefaultHttpClient(); return httpClient.execute(requestBase); } @Override protected void onPostExecute(T result) { if(!wasCancelled && postTask != null){ postTask.doTask(result, statusCode); } } @Override public void cancelTask(){ wasCancelled = true; } } @Deprecated private static class ImageLoadingAsyncTask extends AsyncTask<Void, Integer, Drawable> implements CancellableTask{ private String imgUrl; private ImageManager.OnImageLoadedListener callback; //private volatile InputStream inputStream; private volatile boolean cancelled = false; public ImageLoadingAsyncTask(String action, ImageManager.OnImageLoadedListener callback){ this.imgUrl = ApiConnection.URL + action; this.callback = callback; } @Override protected Drawable doInBackground(Void... params) { InputStream inputStream = null; try{ inputStream = (InputStream) new java.net.URL(imgUrl).getContent(); if(!cancelled){ Drawable d = Drawable.createFromStream(inputStream, "src name"); return d; } } catch (MalformedURLException e) { e.printStackTrace(); } catch(FileNotFoundException e){ Log.e("ApiConnection", "File was not found: " + imgUrl); return null; } catch(IOException e) { e.printStackTrace(); }finally{ if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } @Override protected void onPostExecute(Drawable drawable) { if(!cancelled && drawable != null){ callback.onImageLoaded(drawable); } } @Override public void cancelTask() { cancelled = true; } } }