1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map;
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson(); private final Class<T> clazz; private Map<String, String> headers; private final Map<String, String> params; private final Response.Listener<T> listener;
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers, Map<String, String> body, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(Method.POST, url, errorListener); this.clazz = clazz; this.headers = headers; this.params = body; this.listener = listener; }
public GsonRequest(int type,String url, Class<T> clazz, Map<String, String> headers, Map<String, String> params, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(type, url, errorListener); this.clazz = clazz; this.headers = headers; this.params = params; this.listener = listener; }
@Override public byte[] getBody(){
byte[] body = null; if(params!=null) { JSONObject jsonObject = new JSONObject(params); body = jsonObject.toString().getBytes(); } return body; }
@Override public Map<String, String> getHeaders() throws AuthFailureError {
if(headers == null){ headers = new HashMap<>(); } headers.put("Content-Type","application/json");
return headers; }
@Override protected void deliverResponse(T response) { listener.onResponse(response); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String( response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success( gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } }
|