Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send form-urlencoded parameters in post request android volley

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?

like image 923
user4071017 Avatar asked Sep 23 '14 15:09

user4071017


1 Answers

Ater a long long struggle, found the solution. You need to override getBodyContentType() and return application/x-www-form-urlencoded; charset=UTF-8.

StringRequest jsonObjRequest = new StringRequest(      Request.Method.POST,     getResources().getString(R.string.base_url),     new Response.Listener<String>() {         @Override         public void onResponse(String response) {              MyFunctions.toastShort(LoginActivity.this, response);         }     },      new Response.ErrorListener() {          @Override         public void onErrorResponse(VolleyError error) {             VolleyLog.d("volley", "Error: " + error.getMessage());             error.printStackTrace();             MyFunctions.croutonAlert(LoginActivity.this,                 MyFunctions.parseVolleyError(error));             loading.setVisibility(View.GONE);         }     }) {      @Override     public String getBodyContentType() {         return "application/x-www-form-urlencoded; charset=UTF-8";     }      @Override     protected Map<String, String> getParams() throws AuthFailureError {         Map<String, String> params = new HashMap<String, String>();         params.put("username", etUname.getText().toString().trim());         params.put("password", etPass.getText().toString().trim());         return params;     }  };  AppController.getInstance().addToRequestQueue(jsonObjRequest); 
like image 159
Bala Vishnu Avatar answered Sep 21 '22 04:09

Bala Vishnu