【问题标题】:How to send json from android to php?如何将json从android发送到php?
【发布时间】:2015-09-10 12:43:51
【问题描述】:

为了将 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 无效(由反斜杠引起)。

php 或 java SDK 中是否有方法提供发送和接收 json 的合同而不会出现此类问题?还是我应该在 php 中重新格式化 json 并删除所有反斜杠?

【问题讨论】:

    标签: java php android json android-volley


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      问题是你尝试在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));

      【讨论】:

      • 你能提供一个使用getBody方法的例子吗?
      • 以及如何在php中获取json?
      • 再次更新了答案。可以在这里找到更明确的答案:stackoverflow.com/questions/8945879/…
      • 我有其他参数要发布的问题如下Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); params.put("lastName", lastName.getText().toString().trim()); ArrayList&lt;Command&gt; commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND); String jsonCommands = new Gson().toJson(commands); params.put("commands", jsonCommands);
      • 您可以将其他参数发布为 url 参数,除非它们太大。然后您必须扩展请求/响应主体表示以支持更复杂的结构。
      【解决方案3】:

      首先是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/

      【讨论】:

      • 我已经检查过了,这是anti-slashes 的问题。但我想使用 volley 库,因为它更灵活且易于使用。
      • Map 参数 = new HashMap();这条线很成问题,那其他类型呢?也许尝试更改为 无论如何我建议只添加一个参数并将其发送到服务器,看看会发生什么,我仍然认为最好使用 JSONObject 更可靠...
      【解决方案4】:

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

      【讨论】:

      • DefaultHttpClient 已弃用。不过还是谢谢你的回答。
      • 如果此答案满足您的需求,请标记为真。
      • 我的问题不在于发布 json,而是关于如何确保从 android 发送的 json 是有效的,以便我可以在 php 中对其进行解码。
      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多