I want to make a POST JSONObjectRequest with form urlencoded parameters. How can I do this? I've tried the following code, but to no avail.
final String api = "http://api.url";
final JSONObject jobj = new JSONObject();
jobj.put("Username", "usr");
jobj.put("Password", "passwd");
jobj.put("grant_type", "password");
final JsonObjectRequest jor = new JsonObjectRequest(
Request.Method.POST,
api, jobj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
//do other things with the received JSONObject
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
};
//add to the request queue
requestqueue.AddToRequestQueue(jor);
I'm getting a 400 bad request with the api call! How can I fix it?
I did it the following way (the content-type of my request-body was application/x-www-form-urlencoded):
I've commented at appropriate places in the code.
Ater a long long struggle, found the solution. You need to override
getBodyContentType()
and returnapplication/x-www-form-urlencoded; charset=UTF-8
.Use this if you have to send like "application/json"
}
try using
StringRequest
like below code:and your body must be like this "username=aa&password=bb&email=XXX@XXX.com"
Volley adds a Content-Type header right before the request is sent out.
You must override this with a custom request object.