send json object request parameter code example
Example 1: jsonObjectRequest = new JsonObjectRequest( Request.Method.GET, url, ecplain
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("CUSTOM_HEADER", "Yahoo");
headers.put("ANOTHER_CUSTOM_HEADER", "Google");
return headers;
}
};
Example 2: jsonObjectRequest = new JsonObjectRequest( Request.Method.GET, url, ecplain
public class VolleyErrorHelper {
public static String getMessage(Object error, Context context) {
if (error instanceof TimeoutError) {
return context.getResources().getString(R.string.generic_server_down);
}
else if (isServerProblem(error)) {
return handleServerError(error, context);
}
else if (isNetworkProblem(error)) {
return context.getResources().getString(R.string.no_internet);
}
return context.getResources().getString(R.string.generic_error);
}
private static boolean isNetworkProblem(Object error) {
return (error instanceof NetworkError) || (error instanceof NoConnectionError);
}
private static boolean isServerProblem(Object error) {
return (error instanceof ServerError) || (error instanceof AuthFailureError);
}
private static String handleServerError(Object err, Context context) {
VolleyError error = (VolleyError) err;
NetworkResponse response = error.networkResponse;
if (response != null) {
switch (response.statusCode) {
case 404:
case 422:
case 401:
try {
HashMap<String, String> result = new Gson().fromJson(new String(response.data),
new TypeToken<Map<String, String>>() {
}.getType());
if (result != null && result.containsKey("error")) {
return result.get("error");
}
} catch (Exception e) {
e.printStackTrace();
}
return error.getMessage();
default:
return context.getResources().getString(R.string.generic_server_down);
}
}
return context.getResources().getString(R.string.generic_error);
}
}