Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringRequest with JSON body

I'm trying to send a request using Volley but I can't figure how to make it work.

I need to send a POST request with JSON encoded data as the body, but after hours of trying different things I still can't make it work.

This is my current code for the request:

User user = User.getUser(context);
String account = user.getUserAccount();
String degreeCode = user.getDegreeCode();

final JSONObject body = new JSONObject();
try {
    body.put(NEWS_KEY, 0);
    body.put(NEWS_DEGREE, degreeCode);
    body.put(NEWS_COORDINATION, 0);
    body.put(NEWS_DIVISION, 0);
    body.put(NEWS_ACCOUNT, account);
} catch (JSONException e) {
    e.printStackTrace();
}

StringRequest request = new StringRequest(Request.Method.POST, GET_NEWS, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(String response) {
        Log.i(TAG, response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Error: " + getMessage(error, context));
        Toast.makeText(context, getMessage(error, context), Toast.LENGTH_SHORT).show();
    }
}) {
    @Override
    public byte[] getBody() throws AuthFailureError {
        return body.toString().getBytes();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        return headers;
    }
};
queue.add(request);

But this code always returns "Bad request error"

Some things I've tried:

  • Override getParams() method instead of getBody(). (Didn't work)
  • Send a JSONObjectRequest with the body on the constructor. This one worked, but because my web service returns a String value I always get a ParseError. That's why I'm using StringRequest.

Any help is very much appreciated.

like image 483
Carlos J Avatar asked Dec 12 '14 19:12

Carlos J


1 Answers

As already mentioned on njzk2's comment, the easiest way is to override getBodyContentType() instead. Overriding getHeaders() could probably work too, but you need to put all necessary headers, not only Content-Type, since you basically override the headers that the original method set.

Your code should look like this:

StringRequest request = new StringRequest(...) {
    @Override
    public byte[] getBody() throws AuthFailureError {
        return body.toString().getBytes();
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }
};
like image 190
2 revs Avatar answered Oct 31 '22 00:10

2 revs