StringRequest with JSON body
Asked Answered
A

1

6

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.

Amphipod answered 12/12, 2014 at 19:51 Comment(1)
I think you want to override getBodyContentType instead of getHeaders (although getHeaders should override getBodyContentType)Baras
T
15

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";
    }
};
Thornhill answered 12/12, 2014 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.