Android Volley - Basicnetwork.Performrequest: Unexpected Response Code 400

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.

As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.

So you can do something similar to this in your error listener:

/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {

// As of f605da3 the following should work
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}

For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.

I hope that they implement that TODO mentioned in the source file.

BasicNetwork.performRequest: Unexpected response code 400 in android

I just had to change the format of JsonObjectRequest(). The correct format is given below as suggested by @ZeekHuge

JsonObjectRequest(int method,
String url,
JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener)

The correct code is given below :

public class Gps3Activity extends AppCompatActivity {

private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
private Button display;
private TextView displayLocation;
private LocationManager locationManager;
private LocationListener locationListener;
private RequestQueue requestQueue;
private double lat;
private double lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps3);

display = (Button) findViewById(R.id.displayL);
displayLocation=(TextView)findViewById(R.id.location1);
requestQueue = Volley.newRequestQueue(this);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new myLocationlistener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);

display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

getLocation(lat,lng);

Log.e("Latitude", String.valueOf(lat));
Log.e("Longitude", String.valueOf(lng));
Log.e("city",address);
Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
displayLocation.setText("City : "+address);
}
});
}

private class myLocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
//Toast.makeText(getApplicationContext(),"Latitude: "+lat+"\nLongitude: "+lng,Toast.LENGTH_LONG).show();
getLocation(lat,lng);
}
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
}

public void getLocation(double latitude,double longitude){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
"http://maps.googleapis.com/maps/api/geocode/json?latlng="+ latitude+","+longitude +"&sensor=true",
new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
try {
address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
//textViewCity.setText(address);
//Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});
requestQueue.add(request);
}
}

Although by using this method it takes a lot of time to display the location.

Volley error: Unexpected response code 400

I'm not sure if this is of any help, but here is how I use Volley for my Login request:

/**
* Method that checks given user credentials with the ones in the online DB
* @param v the view that activated this method
*/
public void logIn(View v) {
final String email = String.valueOf(((EditText) findViewById(R.id.inputEmail)).getText());
final String password = String.valueOf(((EditText) findViewById(R.id.inputPassword)).getText());

String tag_string_req = "string_req";
final String TAG = AppController.class
.getSimpleName();
String url = "http://android.diggin.io/diggin/v1/login";
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d(TAG, response);
try {
final JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.getBoolean("error")) {
apiKey = jsonObject.getString("apiKey");
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.apiKey), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.apiKey), apiKey);
editor.commit();
refreshApiKey();
} else {
//Send message when something goes wrong
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(LoginActivity.this);
try {
dlgAlert.setMessage(jsonObject.getString("message"));
} catch (JSONException e) {
dlgAlert.setMessage("Something went wrong, please try again");
}
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//Send message when something goes wrong
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(LoginActivity.this);
dlgAlert.setMessage("Error while logging in, please try again");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
});
}
}) {

@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);

return params;
}
};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

Error Android Volley Unexpected response code 400

try changing Request.Method.PUT to Request.Method.POST since you are trying to get data with StringRequest.



Related Topics



Leave a reply



Submit