2

i'm using the following code to post a json object to php server :

    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put("tag", "jsonParams");
    JSONObject jsonObject = new JSONObject(paramsMap);
    Log.d("JSON", jsonObject.toString());
    JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("JSON RESPONSE", response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("JSON ERROR", error.getMessage());
                }
            });


    requestQ.add(jsonRequest);

and using this to receive the object in php:

    $body = '';
    $handle = fopen('php://input','r');
    while(!feof($handle)){
        $body .= fread($handle,1024);
    }
    $logger->log("login request","request body: ".$body);

the problem is that the $body is always empty i used FIDDLER to check my HTTP request and it's there as raw data like this : {"tag":"jsonParams"} so what am i messing ? thx in advance.

Bassel Shmali
  • 207
  • 2
  • 15
  • which listener is being called? onResponse or onErrorResponse? – random Apr 21 '15 at 05:17
  • onResponse, i'm sending a JsonObject back and it's being received correctly. – Bassel Shmali Apr 21 '15 at 06:46
  • I had the exact same problem and fixed it by changing volley's version as explained here [http://stackoverflow.com/questions/16659620/volley-android-networking-library/]. I hope it helps – Sylvain Biehler May 04 '15 at 14:40
  • Hey.. did you find a solution? – Lisitso Jun 09 '16 at 12:47
  • @Lisitso, No, I didn't have much time to investigate the issue further so I dropped it, I remember that I appended the JSONObject as a post param in the request and I recieved that param at backend and parsed it as a json, I think the problem was that the post body is json as whole and php expects params as key-value... – Bassel Shmali Jun 09 '16 at 22:14

2 Answers2

0

I know this is an old question, but for future readers...

I have solved the exact same problem by using StringRequest instead of JsonObjectRequest. The constructor differs just very slightly and you can then easily parse string response to JsonObject like this:

JSONObject response = new JSONObject(responseString);
LordMsz
  • 154
  • 3
  • 5
0

Not sure what was your problem, but for the future googlers:

My problem was that I wasn't reading from php://input

Full code (working):

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);

Clarification: display and result are two TextView objects I am using to display data on the screen, and queue is Volley's request queue.

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

Your Android Monitor should output sth. like :

{
    "foo":"bar",
    "input":{
        "new key":0.8523024722406781,
        "weburl":"hashincludetechnology.com",
        "header": {
            "devicemodel":"Android SDK built for x86",
            "deviceVersion":"7.1",
            "language":"eng"
        }
    }
}
Luka Govedič
  • 399
  • 4
  • 14