When I am trying to fetch data through rest api using Volley StringRequest or JsonObjectRequest. I always get 400 error. Its working fine with the postman. Http request method is POST, Content-Type is application/x-www-form-urlencoded. I have also checked my parameter spelling and it looks fine to me. I have tried with both StringRequest and JsonObjectRequest, result is E/Volley: [10283] BasicNetwork.performRequest: Unexpected response code 400. Below is my code. I have attached a screenshot.
Here is the new screenshot
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
viewHelper.hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
viewHelper.hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, "Authenticating User");
I have alos tried with volley JSONObjectRequest
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_LOGIN, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
Can anyone please help me in fixing this issue.
Below is the working example of POST request using Volley library.
Add this to your build.gradle (Module:app) -
compile 'com.mcxiaoke.volley:library:1.0.19'
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
progressDialog.dismiss();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
if(jsonObject.has("success")){
if(jsonObject.getBoolean("success") == true){
JSONObject userObject = new JSONObject(jsonObject.getString("user"));
Map<String, String> loginDetails = new HashMap<String, String>();
loginDetails.put(KEY_IS_LOGGED_IN, "true");
loginDetails.put(ACCESS_TOKEN, jsonObject.getString(ACCESS_TOKEN));
loginDetails.put(USERID, userObject.getString(USERID));
loginDetails.put(FIRSTNAME, userObject.getString(FIRSTNAME));
loginDetails.put(LASTNAME, userObject.getString(LASTNAME));
loginDetails.put(EMAIL, userObject.getString(EMAIL));
session = new SessionManager(_myActivity);
session.setLogin(loginDetails);
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
intent.putExtra("FROM_ACTIVITY", "LoginActivity");
startActivity(intent);
LoginActivity.this.finish();
}else{
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
Toast.makeText(getApplicationContext(), "Username or Password does not matched!", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong, Please try agian", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
progressDialog.dismiss();
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
mRequestQueue.add(stringRequest);
Please comment if anyone faced issue with above code.
Thanks to everyone who tried to help me.
A 400 means bad request the data sent by the you to the server didn't follow the rules.So check your parameter or spelling of these parameter which is required by server.
So check those try again hope it work for you :)
Unexpected response code 400 means Bad Reuest.
This Response is caused by sending wrong parameters with the URL.
To solve:
Check every parameter with spelling.
Make sure if response is obtained in string or in object. stringRequest or JSONObjectReuest
Also check Content-type
use this as Content-type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
For JsonObjectReuest use:
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "BLah");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response:", response.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.getMessage());
}
});
Related
The postman response is this image:
This is the code i am using to send the data in the post request. Although i am getting a 400 response code from this.
StringRequest stringRequest = new StringRequest(Request.Method.POST,
API.ADD_PAYMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
onBackPressed();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(AddPaymentActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("amount", "123");
params.put("description", "Not Paid");
params.put("customer", "1");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=UTF-8");
headers.put("Authorization", "token 0ee1248c5a84e8b1e36a8a15da48c0bb7580926c");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AddPaymentActivity.this);
requestQueue.add(stringRequest);
First of all why don't you use JsonObjectRequest instead of StringRequest when you're using application/json as your talking language with server? Second have you tried passing your parameters to the other request constructor like below?
Map<String, Object> params = new HashMap<>();
params.put("amount", 123);
params.put("description", "Not Paid");
params.put("customer", 1);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, API.ADD_PAYMENT, new JSONObject(params), new Response.Listener<JSONObject>() {
...
Passing your headers are essential so the rest of you code remains as it is.
I am adding contacts to active campaign api but the request is not sending the post parameters.The parameters are being sent from postman but with volley its not working. I have tried sending params from the constructor also but no progress. Here is the code.
Map<String, String> params = new HashMap();
params.put("email", "wff#dd.com");
params.put("p[1]", "1");
//JSONObject parameters = new JSONObject(params);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
url="https://brumano.api-us1.com/admin/api.php?api_key=key&api_action=contact_add&api_output=json";
Log.d("url",url);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("url",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("url",error.toString());
error.printStackTrace();
}
}){
#Override
public byte[] getBody() {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("email", "w#sss.com");
params2.put("p[1]", "1");
return new JSONObject(params2).toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded;";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params2 = new HashMap<String, String>();
params2.put("email", "w#sss.com");
params2.put("p[1]", "1");
return params2;
}
}
};
queue.add(jsObjRequest);
Try this using StringRequest
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,
"https://brumano.api-us1.com/admin/api.php?api_key=key&api_action=contact_add&api_output=json",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("url",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
}
}) {
#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("email", "w#sss.com");
params.put("p[1]", "1");
return params;
}
};
queue.add(jsonObjRequest);
check this, with stringRequest like this
//Tested on PostMan
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userName", "cyborg91mv#gmail.com");
params.put("password", "qwerty");
System.out.println(params);
return params;
}
Now if your server expects json, then make jsonRequest
JSONObject jsonObjectBody = new JSONObject();
jsonObjectBody.put("userName", "cyborg91mv#gmail.com");
jsonObjectBody.put("password", "qwerty");
I am trying hit an api(written in PHP) and posting params with it.
Here is my code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
})
{
#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;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params.
I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?
Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems.
There is my code:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
String no = jsonObject.getString("$PhoneNo");
} catch (JSONException e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley " + error.toString());
}
})
{
#Override
public String getBodyContentType() {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
//return pars;
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
However I am still trying to figure out why JsonobjectRequest did not work.
As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."
And after searching again, I saw this thread.
if you are sending your data in raw format you need to try this,first of all make json of your data to be post.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
and you have to override these methods
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
if you also have header in your post request you also send that with by following type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
params.put("Authorization", auth_token);
return params;
}
Here is the whole code.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String token = jsonObject.getString("token");
prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);
if (status == 1) {
startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
} else if (status == 0) {
Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyApplication.getInstance().addToReqQueue(sr, "jreq");
}
} catch (Exception e) {
}
Try migrating to getHeaders and remove getParams
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return pars;
}
Or - Reuse the getParams method
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = getParams();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
If it is a body request all you need to do is add the extra parameter.
JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc#xyz.com");
body.put("pass", "a");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, body,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
});
I am using volley library for making request. I need to post param as json array because I am receiving it on the other side as json array. How can I convert my params to Json array?
here is my code
public void SendData() {{
final StringRequest strReq = new StringRequest(Request.Method.POST, GET_STUDENTS_BY_ID, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("failedd",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
}
})
{
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("student_id", studId);
params.put("to", tomail);
params.put("subject", subjects);
params.put("description", descriptions);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
please help..
public void SendData() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("student_id", studId);
params.put("to", tomail);
params.put("subject", subjects);
params.put("description", descriptions);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,GET_STUDENTS_BY_ID,parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
the JSONObject is this:
{"tag":"login","success":1,"error":0,"name":"pb","dir":"DH","br":"LL","gr":"IW","email":"empty"}
logcat says:
Value Access of type java.lang.String cannot be converted to JSONObject
the running an AsyncTask beside, and it works. why the volley-code says its a string? The answer from the server is a JSONObject for sure.... Why it says its a String?
private void makeJsonObjectRequest() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String dir = response.getString("dir");
Log.d("dir", dir);
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSONException", e.getMessage().toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse", error.getMessage().toString());
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("name", name);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
I don't know why it's append but I got the same issue with volley with the same type of request (HTTP POST + HEADER + PARAMS)
I fix it using StringRequest and parsing it manually. Try in this way
StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d(TAG, "Success "+ s.toString());
try {
JSONObject data = new JSONObject(s);
String dir = data.getString("dir");
Log.d("dir", dir);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error response " + error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("name", name);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
While the workaround with the StringRequest works fine, I found the "real" problem which is a very unintuitive default implementation in Volley which causes the POST request to turn into a GET. Check out my answer here
for a solution.