volley studio method jsonobjectrequest example consumir android rest android-volley

studio - volley android post



Android Volley me da error 400 (12)

Estoy intentando realizar una solicitud POST a mi API y funciona en Postman (obtengo un objeto JSON válido), pero no uso Volley . Con el siguiente código:

String URL = "http://somename/token"; RequestQueue queue = Volley.newRequestQueue(StartActivity.this); queue.add(new JsonObjectRequest(Method.POST, URL, null, new Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // handle response Log.i("StartActivity", response.toString()); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handle error Log.i("StartActivity", error.toString()); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("username", "someUsername"); headers.put("password", "somePassword"); headers.put("Authorization", "Basic someCodeHere"); return headers; } @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("grant_type", "client_credentials"); return params; } });

Obtuve el siguiente error:

02-12 21:42:54.774: E/Volley(19215): [46574] BasicNetwork.performRequest: Unexpected response code 400 for http://somename/token/

He visto muchos ejemplos y realmente no veo qué está mal aquí. Alguien tiene alguna idea?

Actualicé el código con este método:

HashMap<String, String> createBasicAuthHeader(String username, String password) { HashMap<String, String> headerMap = new HashMap<String, String>(); String credentials = username + ":" + password; String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); headerMap.put("Authorization", "Basic " + base64EncodedCredentials); return headerMap; }

y cambié getHeaders() a:

@Override public Map<String, String> getHeaders() throws AuthFailureError { return createBasicAuthHeader("username", "password"); }

¡Sigue recibiendo el mismo error!


400 error es porque Content-Type está mal configurado. Por favor haga lo siguiente.

  1. La función GetHeader debería ser como

    @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> param = new HashMap<String, String>(); return param; }

  2. Agregue esta nueva función de anulación.

    @Override public String getBodyContentType() { return "application/json"; }


400 indica una solicitud incorrecta, tal vez falte Content-Type=application/json en sus encabezados


Algunas veces, este error 400 se produce debido al tipo de Solicitud, por lo que necesita cambiar el Método de Solicitud.GET para el Método.PESO de Solicitud y luego funciona como un encanto.


Compruebe si está utilizando el SDK correcto

Para Android Studio / IntelliJIDEA:

File -> Project Structure -> Project -> Project SDK Modules -> Check each modules "Module SDK"

Preferiblemente, deberías usar "Google API (xx)" en lugar de Android API


En Android 2.3 hay un problema al usar Base64.encodeToString () ya que introduce una nueva línea en el encabezado HTTP. Vea mi respuesta a esta pregunta aquí en SO.

Respuesta corta: no use Base64.encodeToString () sino que coloque la cadena ya codificada allí.


He eliminado este params.put ("Content-Type", "application / x-www-form-urlencoded");

Este es mi cambio de código.

@Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); if(!isLogout) { params.put("username", username); params.put("password", password); params.put("grant_type", "password"); } else { } return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String,String> params = new HashMap<String, String>(); if(isLogout) { params.put("Authorization", "bearer "+LibraryDataModel.getToken()); }else { // Removed this line // params.put("Content-Type", "application/x-www-form-urlencoded"); } return params; }


He encontrado una solución si estás usando un cartero para golpear la API y tu API ha definido un campo de serializador como skill = serializers.JSONField (), entonces ocurrió ese tipo de error.

Solución Para POSTMAN : solo agrega binary = True dentro de JSONField ex- skill = serializers.JSONField (binary = True)

Solución para Android u otro cliente, entonces, solo elimine binary = True dentro de JSONField ex- skill = serializers.JSONField ()


Puede haber múltiples razones para este error.

Una razón, por supuesto, como han dicho otros, es que quizás falte o haya configurado incorrectamente el encabezado "Tipo de contenido".

Si lo ha implementado correctamente, otra posible razón es que está enviando parámetros directamente desde su URL. Puede haber un caso en el que params sea una cadena con algunos espacios en blanco. Estos espacios en blanco causan problemas en las solicitudes GET a través de Volley. Necesitas encontrar otra forma de evitarlo. Eso es todo.


Si está pasando el valor json a in body (raw json). No es necesario establecer el tipo de contenido como headers.put ("Content-Type", "application / json; charset = utf-8");

Cuando estaba usando el tipo de contenido en la devolución de llamada del encabezado, el estado de respuesta 400 estaba obteniendo en logcat. Comenté headers.put ("Content-Type", "application / json; charset = utf-8"); como porque estoy pasando raw json en el cuerpo mientras llamo a api.screenshot para el cartero está adjunto. Ayudará

private void volleyCall(String email, String password) { RequestQueue queue= Volley.newRequestQueue(this); String URL = "http://XXXX.in:8080/XXXX/api/userService/login"; Map<String, String> jsonParams = new HashMap<S[enter image description here][1]tring, String>(); jsonParams.put("email", email); jsonParams.put("password", password); Log.d(TAG,"Json:"+ new JSONObject(jsonParams)); JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, URL,new JSONObject(jsonParams), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG,"Json"+ response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle Error Log.d(TAG, "Error: " + error + "/nStatus Code " + error.networkResponse.statusCode + "/nResponse Data " + error.networkResponse.data + "/nCause " + error.getCause() + "/nmessage" + 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; } @Override public String getBodyContentType() { return "application/json"; } }; queue.add(postRequest); }

LogCat: LoginActivity: Json:{"email":"[email protected]","password":"abcde"} LoginActivity: Error: com.android.volley.ServerError Status Code 400 Response Data [B@63ca992 Cause null messagenull


Tengo el mismo problema antes y obtuve la solución en mi proyecto:

RequestQueue requestManager = Volley.newRequestQueue(this); String requestURL = "http://www.mywebsite.org"; Listener<String> jsonListerner = new Response.Listener<String>() { @Override public void onResponse(String list) { } }; ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.w("Volley Error", error.getMessage()); } }; StringRequest fileRequest = new StringRequest(Request.Method.POST, requestURL, jsonListerner,errorListener){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> params = new HashMap<String, String>(); params.put("token", account.getToken()); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); // do not add anything here return headers; } }; requestManager.add(fileRequest);

En el fragmento de código anterior, utilicé Método de publicación:

Mi respuesta se basa en mi experiencia, así que toma nota:

1.) Cuando use el método POST, use "StringRequest" en lugar de "JsonObjectRequest"

2.) dentro de getHeaders Anula el valor con un HashMap vacío

example snippet: @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> params = new HashMap<String, String>(); params.put("token", account.getToken()); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); // do not add anything here return headers; }

Y todo funciona en mi caso.


Tengo este error y ahora lo he arreglado. Hice lo que se dice en este enlace . Lo que necesitas hacer es

  1. vaya a src / com / android / volley / toolbox / BasicNetwork.java
  2. Cambia las siguientes lineas

if (statusCode < 200 || statusCode > 299) { throw new IOException(); }

con

if (statusCode < 200 || statusCode > 405) { throw new IOException(); }

Espero que esto ayude.


Tuve el mismo problema y quité del encabezado:

headers.put("Content-Type", "application/json");

Ahora funciona muy bien!