StringRequest with JSON body
I'm trying to send a request using Volley, but I can't figure out how to get it to work.
I need to send a POST request with JSON encoded data as body, but after hours of trying different things, I still can't get it to 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:
- Cancel
getParams()
insteadgetBody()
. (Does not work) - Send a
JSONObjectRequest
with a body in the constructor. This worked, but since my webservice is returning a valueString
, I always getParseError
. This is why I am usingStringRequest
.
Any help is greatly appreciated.
source to share
As mentioned in njzk2's comment , the easiest way is to override getBodyContentType()
. Perhaps overriding getHeaders()
could work too, but you need to put all the headers you need, not just Content-Type
as you are basically overriding the headers set by the original method.
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";
}
};
source to share