Java tutorial
/** * Project: warnme-app * File: GsonHttpResponseHandler.java * License: * This file is licensed under GNU General Public License version 3 * http://www.gnu.org/licenses/gpl-3.0.txt * * Copyright: Bartosz Cichecki [ cichecki.bartosz@gmail.com ] * Date: Mar 27, 2014 */ package dtu.ds.warnme.app.ws.client.https; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; import android.util.Log; import com.google.gson.Gson; import com.loopj.android.http.TextHttpResponseHandler; /** * @author Bartosz Cichecki * */ public abstract class GsonHttpResponseHandler<T> extends TextHttpResponseHandler { private static final String TAG = "GsonHttpResponseHandler"; private Type type; private Gson gson = new Gson(); public GsonHttpResponseHandler(Type type) { super(); this.type = type; } public GsonHttpResponseHandler(Type type, String encoding) { super(encoding); this.type = type; } @Override @Deprecated public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { try { String response = responseBody != null ? new String(responseBody, getCharset()) : StringUtils.EMPTY; onFailure(statusCode, headers, response, error); } catch (UnsupportedEncodingException e) { Log.v(TAG, "String encoding failed, calling onFailure(int, Header[], String, Throwable)"); onFailure(0, headers, (String) null, e); } } @Override public abstract void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error); @Override @Deprecated public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { String response = responseBody != null ? new String(responseBody, getCharset()) : StringUtils.EMPTY; T object = gson.fromJson(response, type); onSuccess(statusCode, headers, object); } catch (UnsupportedEncodingException e) { Log.v(TAG, "String encoding failed, calling onFailure(int, Header[], String, Throwable)"); onFailure(0, headers, (String) null, e); } } public abstract void onSuccess(int statusCode, Header[] headers, T object); }