Skip to content

Instantly share code, notes, and snippets.

@AlecTaylor
Created September 17, 2016 10:11
Show Gist options
  • Save AlecTaylor/e1fbc2c1545b5a48557ca5b6b677e428 to your computer and use it in GitHub Desktop.
Save AlecTaylor/e1fbc2c1545b5a48557ca5b6b677e428 to your computer and use it in GitHub Desktop.
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.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
public class JsonResponseRequest extends JsonObjectRequest {
private final Response.Listener<JSONObject> mListener;
/**
* Creates a new request with the given method.
*
* @param method the request {@link Method} to use
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public JsonResponseRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
mListener = listener;
}
/**
* Creates a new GET request.
*
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public JsonResponseRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
this(Request.Method.GET, url, jsonRequest, listener, errorListener);
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(new JSONObject(new String(response.data,
HttpHeaderParser.parseCharset(response.headers))),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment