2017-04-19 4 views
-1

J'essaie de faire une requête JSON en utilisant la bibliothèque Volley à un serveur php, mais pour une raison quelconque, le serveur ne reçoit pas l'objet json que j'envoie , et il répond avec une chaîne vide. Voici mon codeAndroid Volley - ne peut pas faire une requête JSON avec POST, obtenant une réponse vide

import android.content.Context; 
import com.android.volley.Request; 
import com.android.volley.RequestQueue; 
import com.android.volley.Response.Listener; 
import com.android.volley.Response.ErrorListener; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.JsonObjectRequest; 
import com.android.volley.toolbox.Volley; 
import org.json.JSONException; 
import org.json.JSONObject; 

public class MyVolley implements Listener, ErrorListener { 

    private static Context appContext; 

    public MyVolley(Context context) { 
     appContext = context; 
    } 

    public void stuff() throws JSONException { 
     RequestQueue queue = Volley.newRequestQueue(appContext); 
     JSONObject obj = new JSONObject(); 
     obj.put("param1", "assda"); 
     obj.put("param2", "fassfafsa"); 
     JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, "some url here", obj, this, this); 
     queue.add(stringRequest); 
    } 

    @Override 
    public void onResponse(Object response) { 
     System.out.println(response); 
    } 

    @Override 
    public void onErrorResponse(VolleyError error) { 
     System.out.println(error); 
    } 
} 

Et quand il exécute, c'est ce que le serveur reçoit

array (
    'Content-Type' => 'application/json; charset=utf-8', 
    'User-Agent' => 'pointless info here', 
    'Host' => 'some host here', 
    'Connection' => 'Keep-Alive', 
    'Accept-Encoding' => 'gzip', 
    'Content-Length' => '107', 
) array (
) array (
) 

Pourquoi pourrait-il se produire?

Répondre

1

Assurez-vous que ce n'est pas une erreur côté serveur (essayez votre service en utilisant Postman par exemple).

J'ai personnellement fait face au même problème il y a quelque temps, changer JsonObjectRequest en StringRequest a résolu mon problème.

Jetez un oeil à ce lien: https://stackoverflow.com/a/31613565/7871886

Maintenant, j'utiliser Retrofit2 au lieu de Volley ... Peut-être une option. heureux de codage

1

Je ne sais pas quel était votre problème, mais pour l'avenir Googlers:

Mon problème était que je tentais de lire sous forme $_POST au lieu de php://input

code complet (travail):

Java:

JSONObject jsonobj; // declared locally so that it destroys after serving its purpose 
jsonobj = new JSONObject(); 
try { 
    // adding some keys 
    jsonobj.put("new key", Math.random()); 
    jsonobj.put("weburl", "hashincludetechnology.com"); 
    // lets add some headers (nested JSON object) 
    JSONObject header = new JSONObject(); 
    header.put("devicemodel", android.os.Build.MODEL); // Device model 
    header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version 
    header.put("language", Locale.getDefault().getISO3Language()); // Language 
    jsonobj.put("header", header); 
    // Display the contents of the JSON objects 
    display.setText(jsonobj.toString(2)); 
} catch (JSONException ex) { 
    display.setText("Error Occurred while building JSON"); 
    ex.printStackTrace(); 
} 

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonobj, new Response.Listener<JSONObject>() { 


    @Override 
    public void onResponse(JSONObject response) { 
     System.out.println("onResponse()"); 

     try { 
      result.setText("Response: " + response.toString(2)) 

      System.out.println("Response: " + response.toString(2)); 
     } catch (JSONException e) { 
      display.setText("Error Occurred while building JSON"); 
      e.printStackTrace(); 
     } 
     //to make sure it works backwards as well 

    } 
}, new Response.ErrorListener() { 

    @Override 
    public void onErrorResponse(VolleyError error) { 
     System.out.println("onErrorResponse()"); 
     System.out.println(error.toString()); 


    } 
}); 


System.out.println("After the request is made"); 
// Add the request to the RequestQueue. 
queue.add(jsObjRequest); 

Précision: display et result sont deux objets TextView que j'utilise pour afficher des données sur l'écran, et queue est la file d'attente de demandes de Volley.

PHP:

$inp = json_decode(file_get_contents('php://input')); //$input now contains the jsonobj 
echo json_encode(["foo"=>"bar","input"=>$inp]); //to make sure we received the json and to test the response handling 

Votre moniteur doit Android STH de sortie. comme:

{ 
    "foo":"bar", 
    "input":{ 
     "new key":0.8523024722406781, 
     "weburl":"hashincludetechnology.com", 
     "header": { 
      "devicemodel":"Android SDK built for x86", 
      "deviceVersion":"7.1", 
      "language":"eng" 
     } 
    } 
}