Android Volley Unexpected response code 400 - android

I am using Volley for a login function but I get unexpected response code 400 for https.
It works on WiFi but does not work on a cellular network and the problem only happens on selected phone models. Below is my code.
public void LoginRequest(final String username,final String password,final ActionResponse success,final Action err ){
RequestQueue queue = MVolleyRequests.getInstance(mContext).getRequestQueue();
StringRequest sr = new StringRequest(com.android.volley.Request.Method.POST,LOGIN_URL,
new Listener<String>() {
#Override
public void onResponse(String response) {
success.action(MError.getError(Integer.parseInt(response)));
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
err.action();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id", username);
params.put("pwd", password);
params.put("version", "2.5" );
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; charset=utf-8");
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MVolleyRequests.getInstance(mContext).addToRequestQueue(sr);
}

Try this out:
JSONObject params = new JSONObject();
try {
params.put("id", username);
params.put("pwd", password);
params.put("version", "2.5" );
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, params,
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());
}
}) {
/**
* Passing some request headers
* */
#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;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
getRequestQueue(jsonObjReq);

Related

BasicNetwork.performRequest - Unexpected response code 400 (POST)

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());
}
});

How to send data with JSONObjectRequest in Volley and I'm getting error Value <br of type java.lang.String cannot be converted to JSONObject

This is JsonObjectRequest and I am getting the error. Help me out......
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("email",email.getText().toString());
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, json_url, new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response.toString());
name.setText(response.getString("Name"));
mobile.setText(response.getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#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;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
Try using volley StringRequest, it seems, server is sending you Strings instead of JsonOBJECTS. If JsonObject is what you need, you must do some changes on the server side. If not try this:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST,
Addresses.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Response", jsonObject .toString());
name.setText(jsonObject .getString("Name"));
mobile.setText(jsonObject .getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#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;
}
};
queue.add(request);
This might be your solution if your server receives values in json form.
JSONObject jsonobject= new JSONObject();
jsonobject.put("email",email.getText().toString());
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, json_url, jsonobject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response.toString());
name.setText(response.getString("Name"));
mobile.setText(response.getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#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;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);

Sending array of integers as a value of volley's params returns 400 code

I am trying to send the following json:
{"communities" : [381, 382, 383, 384, 385]}
I do not have problemst using this code when I am trying to send a hash map with String as key and value but in this case when the value should be array of integers the server doesn't recognize it as such and returns me code 400:
JSONObject dataToPost = new JSONObject();
JSONArray jsa = new JSONArray();
jsa.put(381);
jsa.put(382);
jsa.put(383);
jsa.put(384);
jsa.put(385);
jsa.put(386);
try {
dataToPost.put("communities", jsa);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject dataFinal = dataToPost;
Log.i("fdsfs", dataFinal.toString());
StringRequest postRequest = new StringRequest(Request.Method.POST, GlobalValues.registerSetCommunities,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
manageSuccessResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
manageErrorResponse(error);
}
}
) {
#Override
public byte[] getBody() {
try {
return dataFinal.toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", "Bearer " + Credentials.getAuthToken(mContext));
return headers;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
GlobalValues.request_timeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(mContext).add(postRequest);
Another way that I tried was with JsonObjectRequest. Here is the code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, GlobalValues.registerSetCommunities, dataFinal, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("SENDMOVE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
manageErrorResponse(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("cache-control", "no-cache");
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + Credentials.getAuthToken(mContext));
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
GlobalValues.request_timeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(mContext).add(request);
Using the second way and removing
headers.put("Content-Type", "application/json");
did the trick.

posting params as json in android volley

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);
}

Android Volley: Put request not updating any data

i'm trying to update some data with android volley but not working. and with postman it works.
my code:
private void aceptarAlerta()
{
mRequestQueue = VolleySingleton.getInstance().getmRequestQueue();
SharedPreferences preferencia = getSharedPreferences("ComuniUsuario", Context.MODE_PRIVATE);
token = preferencia.getString("ComuniToken", null);
StringRequest stringRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respuesta: ", response);
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("estado", "true");
params.put("cuidador", Tmensaje[2]);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token " + token);
return headers;
}
#Override
public RetryPolicy getRetryPolicy() {
return new DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
};
mRequestQueue.add(stringRequest);
}
and if i delete params from code i dont get any error response from server.
i don't know what's the problem, i think have a logical error.

Categories

Resources