Pass Parameter with Volley POST

The server code is expecting a JSON object is returning string or rather Json string.

JsonObjectRequest

JSONRequest sends a JSON object in the request body and expects a JSON object in the response. Since the server returns a string it ends up throwing ParseError

StringRequest

StringRequest sends a request with body type x-www-form-urlencoded but since the server is expecting a JSON object. You end up getting 400 Bad Request

The Solution

The Solution is to change the content-type in the string request to JSON and also pass a JSON object in the body. Since it already expects a string you response you are good there. Code for that should be as follows.

StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        mView.showMessage(response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mView.showMessage(error.getMessage());
    }
}) {
    @Override
    public byte[] getBody() throws AuthFailureError {
        HashMap<String, String> params2 = new HashMap<String, String>();
        params2.put("name", "Val");
        params2.put("subject", "Test Subject");
        return new JSONObject(params2).toString().getBytes();
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }
};

Also there is a bug here in the server code

var responseMessage = $"Hello {personToGreet}!";

Should be

var responseMessage = $"Hello {name}!";

Leave a Comment