简体   繁体   English

如何将json从android发送到php?

[英]How to send json from android to php?

To post json from android to php, i used Volley library StringRequest object. 要将json从android发布到php,我使用了Volley库StringRequest对象。

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 为了捕获php中的数据并验证它是否被正确发送,我使用了这个

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. 我注意到,当使用Volley库发送带有POST方法的json字符串时,添加了许多反斜杠来转义双引号。

So here comes my problem: 所以这是我的问题:

I want to decode json to an array of objects in php, so i used 我想将json解码为php中的一个对象数组,所以我使用了

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

But it always returns an empty array because of the invalide above json (caused by the anti-slashes). 但它总是返回一个空数组,因为json上面的invalide(由反斜杠引起)。

Is there a method in php or in java SDK providing a contract for sending and receiving json without having this kind of problems? 在php或java SDK中是否有一个方法提供发送和接收json的合同而没有这种问题? Or should i reformat the json in php and delete all the anti-slashes? 或者我应该重新格式化PHP中的json并删除所有的反斜杠?

The problem is that you try to send the json data in the URL parameters. 问题是您尝试在URL参数中发送json数据。

You need to override the getBody() method to return the json data as request body, not as url parameters. 您需要覆盖getBody()方法以将json数据作为请求主体返回,而不是作为url参数。

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: 然后在PHP中你可以:

$jsonRequest = json_decode(stream_get_contents(STDIN));

first there is problem with the json itself is not build correctly is better to JSONObject for this, for example: 首先是json本身没有正确构建的问题对于JSONObject更好,例如:

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/ 您可以通过复制字符串来检查解析是否成功,并将其复制到在线解析器中,如http://json.parser.online.fr/

Finally, I solved my problem using a custom json_decode method in order to clean the json string before decoding it. 最后,我使用自定义json_decode方法解决了我的问题,以便在解码之前清理json字符串。

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

You can use this method to send json to web service. 您可以使用此方法将json发送到Web服务。

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;


    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM