5

To post json from android to php, i used Volley library StringRequest object.

StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // some code
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //some code
            }
        }){
            @Override
            protected Map<String,String> getParams(){
                Map<String, String> params = new HashMap<String, String>();
                ArrayList<Command> commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND);
                String jsonCommands = new Gson().toJson(commands);
                params.put("commands", jsonCommands);
                return params;
            }
        };

And to catch the data in php and verify if it was sent correcttly, I used this

echo $_POST["commands"]; 

Output:

[{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"CF77 COIN FINDER\",\"url_image\":\"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg\",\"name\":\"CF77 COIN FINDER\",\"pid\":12,\"price\":500.0},\"product_quantity\":3},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"JEOSONAR 3D DUAL SYSTEM\",\"url_image\":\"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg\",\"name\":\"JEOSONAR 3D DUAL SYSTEM\",\"pid\":15,\"price\":500.0},\"product_quantity\":1},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"MAKRO POINTER\",\"url_image\":\"IMG_Macro.jpg\",\"name\":\"MAKRO POINTER\",\"pid\":18,\"price\":500.0},\"product_quantity\":3}]

I have noticed that when sending the json string with POST Method using Volley library, a lot of anti-slashes have been added to escape double quotes.

So here comes my problem:

I want to decode json to an array of objects in php, so i used

$commands = json_decode( $_POST["commands"],true);

But it always returns an empty array because of the invalide above json (caused by the anti-slashes).

Is there a method in php or in java SDK providing a contract for sending and receiving json without having this kind of problems? Or should i reformat the json in php and delete all the anti-slashes?

MChaker
  • 2,610
  • 2
  • 22
  • 38

4 Answers4

2

The problem is that you try to send the json data in the URL parameters.

You need to override the getBody() method to return the json data as request body, not as url parameters.

Eg:

/**
 * Returns the raw POST or PUT body to be sent.
 *
 * @throws AuthFailureError in the event of auth failure
 */
public byte[] getBody() throws AuthFailureError {
    return new Gson().toJson(commands).getBytes();
}

And then in PHP you can:

$jsonRequest = json_decode(stream_get_contents(STDIN));

Andrei Mărcuţ
  • 1,273
  • 17
  • 28
  • Can you provide an example of using the `getBody` method? – MChaker Jun 24 '15 at 10:53
  • And How to get the json in php? – MChaker Jun 24 '15 at 11:03
  • Updated the answer again. A more explicit answer can be found here: http://stackoverflow.com/questions/8945879/how-to-get-body-of-a-post-in-php – Andrei Mărcuţ Jun 24 '15 at 11:05
  • The problem that i have other params to post them as follow `Map params = new HashMap(); params.put("lastName", lastName.getText().toString().trim()); ArrayList commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND); String jsonCommands = new Gson().toJson(commands); params.put("commands", jsonCommands);` – MChaker Jun 24 '15 at 11:09
  • You can post other params as url params, unless they are too large. Then you'd have to extend the request/response body representation to support more complex structures. – Andrei Mărcuţ Jun 24 '15 at 11:11
1

first there is problem with the json itself is not build correctly is better to JSONObject for this, for example:

JSONObject js = new JSONObject();
try {
       js.put("value",10);
} catch (JSONException e) {
       e.printStackTrace();
}
String jss = js.toString();

you can check if the parse is success by copy the string and copy it in online parser like this http://json.parser.online.fr/

Proxytype
  • 712
  • 7
  • 18
  • I have checked that and it was a problem of the `anti-slashes`. But i want to use volley library because it is more flexible and easy to use. – MChaker Jun 24 '15 at 11:03
  • Map params = new HashMap(); this line is very problematic, what about other types? maybe try to change to anyway i recommend that add only one parameter and send it to the server and see what happen, i still think is better to use the JSONObject is more solid... – Proxytype Jun 24 '15 at 11:12
0

Finally, I solved my problem using a custom json_decode method in order to clean the json string before decoding it.

function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
    // search and remove comments like /* */ and //
    $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);
    // search and remove all backslashes
    $json = str_replace("\\","", $json);

    if(version_compare(phpversion(), '5.4.0', '>=')) {
        $json = json_decode($json, $assoc, $depth, $options);
    }
    elseif(version_compare(phpversion(), '5.3.0', '>=')) {
        $json = json_decode($json, $assoc, $depth);
    }
    else {
        $json = json_decode($json, $assoc);
    }

    return $json;
}
MChaker
  • 2,610
  • 2
  • 22
  • 38
-1

You can use this method to send json to web service.

public String makeServiceCallSubmit(String url, int method,
            JSONArray object) {

        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {

                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-type", "application/json");


                StringEntity se = new StringEntity(object.toString()); 
              //  se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httpPost.setEntity(se); 
                httpResponse = httpClient.execute(httpPost);

            } 
            httpEntity = httpResponse.getEntity();
            Response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Response;


    }
Amee
  • 29
  • 7
  • 1
    `DefaultHttpClient` is deprecated. But thanks for the answer anyway. – MChaker Jun 24 '15 at 10:49
  • If this answer fullfill your need then please mark true to the answer. – Amee Jun 24 '15 at 10:50
  • My problem isn't about posting the json, instead it is about how to ensure that the json sent from android is valid so that i can decode it in php. – MChaker Jun 24 '15 at 10:52