簡體   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