2015-06-09 1 views
11

Così sto facendo un POST JSonObjectRequest al mio server e quando ha successo funziona tutto e le informazioni sono pubblicate, ma se c'è un errore e cerco di visualizzarlo in un toast , si presenta come vuoto. Ecco la mia richiesta:Android Volley error.getMessage() è vuoto

private void logUserIn() { 
    final String URL = Globals.BASE_URL +"/auth/login/"; 
    // Post params to be sent to the server 
    HashMap<String, String> params = new HashMap<String, String>(); 
    params.put("username", username.getText().toString()); 
    params.put("password", password.getText().toString()); 

    JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params), 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        try { 
         Log.d("Log In User", response.toString()); 

         //logged in db, changes screens 
         Intent nextScreen = new Intent(getApplicationContext(), MyProfile.class); 
         startActivity(nextScreen); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); 
      VolleyLog.e("Error: ", error.getMessage()); 
     } 
    }); 

    // add the request object to the queue to be executed 
    Globals.mRequestQueue.add(req); 
} 

error.getMessage() è sempre vuoto. Ecco la mia risposta (testata utilizzando CURL) quando il server restituisce un errore:

{ "non_field_errors": [ "Impossibile accedere con le credenziali fornite." ] }

Non riesco a stampare questo messaggio. Cosa mi manca? Il POST funziona ma la risposta all'errore viene visualizzata in bianco ...

risposta

24

L'oggetto VolleyError ha un riferimento a NetworkResponse, prova a controllarlo per vedere se è possibile ottenere alcune informazioni utili da lì.

@Override 
public void onErrorResponse(VolleyError error) { 
    if (error == null || error.networkResponse == null) { 
     return; 
    } 

    String body; 
    //get status code here 
    final String statusCode = String.valueOf(error.networkResponse.statusCode); 
    //get response body and parse with appropriate encoding 
    try { 
     body = new String(error.networkResponse.data,"UTF-8"); 
    } catch (UnsupportedEncodingException e) { 
     // exception 
    } 

    //do stuff with the body... 
} 
+0

Fantastico! È stato un momento così difficile farlo. Grazie per l'aiuto. – mikebertiean

+1

Come nota a margine, dovresti inserire la riga statusCode all'interno dell'istruzione if perché darà un puntatore nullo se non ci sono risposte dal server. – mikebertiean

+0

grazie salvato la mia giornata –