user3290180
user3290180

Reputation: 4410

Android Volley: how to make json request without returned object?

Now I'm doing

 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, uri, json,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        // do action
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //manage error
                    }
                }
        );

My servlet uses Jersey as JAX-RS. The resource called by the uri passed as parameter does not produce any json object. If I do this way, the error callback is called even if the json object sent with POST is correctly used on server. If I return a json with fake data then the response callback is called, but I don't need to send back an object (wasting the user's data bandwidth). I'd like to do the normale response action if the code of response is OK or 200. How should I do?

Upvotes: 2

Views: 1701

Answers (1)

Jahnold
Jahnold

Reputation: 7683

You can override the parseNetworkResponse method of JsonObjectRequest so that it accepts null responses:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.POST, uri, json,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    // do action
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //manage error
                }
            }
        ) {

        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {


            try {
                String json = new String(
                        response.data,
                        "UTF-8"
                );

                if (json.length() == 0) {
                    return Response.success(
                            null,
                            HttpHeaderParser.parseCacheHeaders(response)
                    );
                }
                else {
                    return super.parseNetworkResponse(response);
                }
            }
            catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            }


        }
    };

Upvotes: 3

Related Questions