如何使用volly将Json String发送到php并解码它?

时间:2016-06-06 07:07:15

标签: php json android-volley

我想将一个json字符串发送到php文件。我知道如何发送字符串值。但我不知道如何发送json字符串并使用php解码它。

这是json的样子。

{"sending_items":[{"order_no":"70000106","items":"example item","items_no":"2000450","plant":"2200","quantity":"2"}]}

这是方法。

private void checkOrderNo() {

        final StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                /*Log.e(TAG, "Inserting Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();*/
                VolleyErrorHandle.handleVolleyErrorTwo(error, pDialog, findViewById(R.id.user_selectItem_root));
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("json_string", json_string);

                return params;
            }
        };

        strReq.setRetryPolicy(new DefaultRetryPolicy(15000, 1,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

这是我的PhP代码..

<?php

    require_once 'include/Config_test.php';

        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
        mysql_select_db(DB_DATABASE,$con) or die("db selection failed");

        $postdata = file_get_contents('php://input'); 
        $data = json_decode($postdata, true);

       if (is_array($data['sending_items'])) {
            foreach ($data['sending_items'] as $record) {
                $order_no = $record['order_no'];
                $items = $record['items'];
                $items_no = $record['items_no'];
                $plant = $record['plant'];
                $quantity = $record['quantity'];

                mysql_query("INSERT INTO tbl_item_list(order_no, items, items_no, plant, quantity) VALUES('$order_no', '$items', '$items_no', '$plant', '$quantity')");

          }
       }

    echo json_encode($data);
    mysql_close($con); 

    ?>

1 个答案:

答案 0 :(得分:1)

根据您的java代码,您将json_string放在名为json_string的参数中,并使用POST方法发送到服务器。

所以你可以在php上获取数据:

<?php
    $jsonString = $_POST['json_string']; 
    $data = json_decode($jsonString);

    //now you can get your JSON data, and do whatever you want :)
?>