I m trying to send json object post request to the server using android volley library.
Here is android side code :
ArrayList<CartItem> jsonSendArray = cartDetails.getShoppingList();
JsonArray array = new Gson().toJsonTree(jsonSendArray, new TypeToken<ArrayList<CartItem>>() {
}.getType()).getAsJsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.add("cartList", array);
Log.i("json_object", new JSONObject(jsonObject.toString()).toString());//this gives me the out-put in log cat {"cartList":[{"size":"M","product_id":1,"qnty":2},{"size":"S","product_id":4,"qnty":1}]}
String url = "http://10.0.2.2:8080/ECommerceApp/getAllProductsAction";
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
new JSONObject(jsonObject.toString()),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.i("response", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley_error", error.toString());
}
});
requestQueue.add(arrayRequest);
And my server side code :
if (request.getParameter("cartList") != null) {
String jsonList = request.getParameter("cartList");
Type type = new TypeToken<List<CartItem>>() {
}.getType();
List<CartItem> conList = new Gson().fromJson(jsonList, type);
List<ProductHasSize> myList = getCompleteProductCart(conList, s);
String element = new Gson().toJson(myList, new TypeToken<List<ProductHasSize>>() {
}.getType());
response.getWriter().write(element);
} else {
JsonArray array = new JsonArray();
JsonObject jo = new JsonObject();
jo.add("error", new JsonPrimitive("Error response"));
array.add(jo);
String element = new Gson().toJson(array);
response.getWriter().write(element);
}
But what I get as the response in android side is :
I/response: [{"error":"Error response"}]
Which means executing else block of the servlet.And also proves request.getParameter("cartList")
is null. Is there anything I have missed in android volley request ?? Any help would be grateful. Thank you.
UPDATE :
Overriding the getParams()
method also give me the same result.
final String jsonString = new Gson().toJson(jsonSendArray, new TypeToken<ArrayList<CartItem>>() {
}.getType());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.i("response", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley_error", error.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("cartList", jsonString);
return params;
}
};