2015-05-14 1 views
8

Ogni volta che provo a utilizzare il metodo POST con Volley, viene visualizzato un errore grave. Ottengo valore null in getCause e un valore predefinito in getNetworkResponse.toString().Errore server Volley con null Risposta di rete

Se utilizzo il metodo GET, funziona correttamente (ottengo risposta dal mio URL).

Qualcuno può aiutare cosa posso fare?

Map<String, String> jsonParams = new HashMap<String, String>(); 
    jsonParams.put("teststr", "abd"); 

    RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue(); 
    JsonObjectRequest request = new JsonObjectRequest(
      Request.Method.POST, 
      url, 
      new JSONObject(jsonParams), 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 

        try { 
         Toast.makeText(getApplicationContext(), "Success"+response.toString(), Toast.LENGTH_LONG).show(); 
        }catch(Exception e){ 
         Toast.makeText(getApplicationContext(), "JSON ERROR", Toast.LENGTH_LONG).show(); 
        } 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Log.d("abd", "Error: " + error 
            + ">>" + error.networkResponse.statusCode 
            + ">>" + error.networkResponse.data 
            + ">>" + error.getCause() 
            + ">>" + error.getMessage()); 
       } 
      }) { 

       @Override 
       protected Map<String,String> getParams() { 
        HashMap<String, String> params = new HashMap<String, String>(); 
        params.put("key", "value"); 
        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; 
       } 
    }; 
    requestQueue.add(request); 

Registro errori:

Error: Error: com.android.volley.ServerError>>404>>[[email protected]>>null>>null

UPDATE: networkResponse.statusCode viene come 404, se l'url è accessibile (e restituire dati se mi basta usare il metodo GET). Se rimuovo la parte di intestazione nel metodo POST, è sempre la stessa.

l'url:

<?php 
    $response = array(); 

    $jsonString = file_get_contents('php://input'); 
    $jsonObj = json_decode($jsonString, true); 

    if(!isset($jsonObj['teststr'])){ 
     $response["msg"] = "No data."; 
    }else{ 
     $response["msg"] = "Success: ".$jsonObj['teststr']; 
    } 
    echo json_encode($response); 
?> 
+0

Hai controllato error.getMessage(); ? – theapache64

+0

Sì, anche questo è nullo – abdfahim

+0

hai una soluzione, sono perso con lo stesso errore e il server risponde normalmente quando testato con postino –

risposta

0

Beh, penso che si può stampare il primo responseCode nel logcat

+0

grazie ... Ho appena aggiornato il mio post .. networkResponse.statusCode = 404 ... sembra che il mio file php abbia qualche problema strutturale (l'url è sicuramente sicuro) – abdfahim

5

In primo luogo, cercare di assicurarsi che il vostro server funziona bene. Puoi usare Postman (chrome plug-in) o qualsiasi altro modo per inviare una richiesta di posta all'URL e vedere quali risposte.

Dopo aver verificato che non ci siano problemi con il server, risolviamo il problema con il volley.

C'è un problema con JsonObjectRequest quando si utilizza il metodo POST. piace questo Volley JsonObjectRequest Post request not working.

Suggerisco di utilizzare prima StringRequest e sovrascrivere il metodo getParams come in precedenza. Dopo aver sopravvissuto a questo compito, puoi provare a scrivere la tua richiesta, non molto difficile ma molto utile.

Suggerisco inoltre di aggiungere request.setShouldCache(false) prima del requestQueue.add(request);. Per impostazione predefinita, volley salva la risposta nella sua cache e questo comportamento può causare qualche strano problema.

+0

grazie, ci proverò .. Btw, ho appena scoperto che se sostituisco il file PHP con un semplice file di testo contenente dati JSON (xxx .json), lo stesso codice funziona bene. Significa qualcosa di speciale? – abdfahim

+0

btw, il POST funziona se eseguo il test con un semplice modulo HTML e provo a ottenere $ _POST variabile su submit. – abdfahim

+0

Quello che so di JsonObjectRequest è che funziona bene con il metodo GET, ma quando usi il metodo POST, semplicemente getParams non viene chiamato. Quindi provo a scrivere la mia richiesta per risolvere questo. –

0

Aggiungere questo codice prima Aggiungi alla coda

request.setRetryPolicy(new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

a volte, è richiesta timeout prima php eseguito completamente. quindi prova questo codice. forse può aiutare

0

Volley non gestisce i parametri del metodo POST integrato perfettamente così per quello è necessario creare una risposta personalizzata.

La risposta è pubblicata da katwal-Dipak su un altro post simile a questo. https://stackoverflow.com/a/31532955/4969957

Che funziona perfettamente. Grazie.

0

forse è legato al proprio operatore ...

Ho lo stesso problema di invio JasonObject con Volley.

Ho testato la mia app su dispositivi 9-10 con due operatori diversi.

La richiesta su un operatore restituisce un errore con tutti i dati nulli o vuoti, nell'altro tutto funziona correttamente e ottengo la risposta dell'API correttamente.

Non ho idea di cosa fanno gli operatori che causano questo problema ... Forse usano una specie di firewall che blocca l'invio di JsonObject.