1

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;
                }
            };
Community
  • 1
  • 1
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36

2 Answers2

1

Dont know this would be a good approach or not. But I managed to work it out like below :

In my android side :

I did override the getHeaders() method

        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.getMessage());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/json");
                params.put("cartList", jsonString);
                return params;
            }

        };

In my Servlet :

I used getHeader("") method instead of using getParameter("")

if (request.getHeader("cartList") != null) {
        String jsonList = request.getHeader("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);

    }

It works fine now . I can get the JSONArray response inside Volley.

Madushan Perera
  • 2,568
  • 2
  • 17
  • 36
  • It is actually not a good idea to send the payload inside the headers. What kind of error where you facing earlier? Did you override both the methods as shown in example? This example approach has been tried by me and is working fine for me. Just a wild guess, is your servlet code written inside the doGet() method? – LearningToCode Mar 06 '16 at 17:56
0

I had the same issue, and it's mainly because on the server side, request.getParameter("cartList") would work with Content-Type="application/x-www-form-urlencoded" and not Content-Type="application/json".

The solution is to use the request.getReader() method and read the JSON string that was sent from the Android client in the POST body of the request.

        BufferedReader bReader = request.getReader();
        String line;
        String jsonList = "";
        if((line = bReader.readLine()) != null)
            jsonList += line;

This is where I got the answer from: https://stackoverflow.com/a/3831791/4938794

Community
  • 1
  • 1
JoeyOggie
  • 26
  • 1
  • 2