繁体   English   中英

如何将json从android发送到php?

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

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

为了捕获php中的数据并验证它是否被正确发送,我使用了这个

echo $_POST["commands"]; 

输出:

[{\"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}]

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

所以这是我的问题:

我想将json解码为php中的一个对象数组,所以我使用了

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

但它总是返回一个空数组,因为json上面的invalide(由反斜杠引起)。

在php或java SDK中是否有一个方法提供发送和接收json的合同而没有这种问题? 或者我应该重新格式化PHP中的json并删除所有的反斜杠?

问题是您尝试在URL参数中发送json数据。

您需要覆盖getBody()方法以将json数据作为请求主体返回,而不是作为url参数。

例如:

/**
 * 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();
}

然后在PHP中你可以:

$jsonRequest = json_decode(stream_get_contents(STDIN));

首先是json本身没有正确构建的问题对于JSONObject更好,例如:

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

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

最后,我使用自定义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;
}

您可以使用此方法将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