将JSONArray发布到php

时间:2016-12-09 07:18:34

标签: java android

我正试图从我的手机获取联系人,但我想将数据发布到php服务以存储在数据库中。检索后,我创建一个名称值对的数组,代码段

      public void getContacts() throws IOException, JSONException {

        List<String> phnnumbers = new ArrayList<String>();
        List<String> names = new ArrayList<String>();

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    System.out.println("name : " + name + ", ID : " + id);
                    names.add(name);
                    // get the phone number
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        System.out.println("phone" + phone);
                        phnnumbers.add(phone);
                    }

                }
            }
Log.d("NAMES",name.toString());
          //  registerContacts(this,URL,names,phnnumbers);
        }
    }

输出是这样的

  [name[]="Chacha Kori, phone[]="+123456987", name[]="Gabuli Somi", [phone[]="+123456789",name[]="Geto Somi", phone[]="+123456789",

如何格式化,以便将其存储在数据库中。我的php端

  function SynchContacts() {

            $phone = $this->input->post('phone');
            $name = $this->input->post('name');       


            for ($i = 0; $i < count($phone); $i++) {
                $data = array(
                    'name' => $name[$i],
                    'phone' => $phone[$i]
                );
                $this->saveData('phonebook', $data);
            }
        }

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

我的建议是不要使用NameValuePair,因为在棒棒糖版本之上,不推荐使用NameValuePair,以便更好地使用Arraylist。

public void getContacts() {

    List<String> phnnumbers = new ArrayList<String>();
    List<String> names = new ArrayList<String>();

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
        null, null, null, null);

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                System.out.println("name : " + name + ", ID : " + id);
                names.add(name);
                // get the phone number
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                    new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    System.out.println("phone" + phone);
                    phnnumbers.add(phone);
                }
                pCur.close();
            }
        }
    }
}

你的Json调用部分应该如下所示,

private static JSONObject post(String sUrl, String body) {
    Log.d("post", sUrl);
    Log.d("post-body", sanitizeJSONBody(body));
    HttpURLConnection connection = null;

    String authentication = "example" + ":" + "exam123ple";
    String encodedAuthentication = Base64
        .encodeToString(authentication.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(sUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization",
            "Basic " + encodedAuthentication);
        connection.setRequestProperty("Accept-Charset", "utf-8,*");
        OutputStreamWriter streamWriter = new OutputStreamWriter(
            connection.getOutputStream());

        streamWriter.write(body);
        streamWriter.flush();
        StringBuilder stringBuilder = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader streamReader = new InputStreamReader(
                connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(
                streamReader);
            String response = null;
            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();

            Log.d("Post-Response",
            sanitizeJSONBody(stringBuilder.toString()));
            return new JSONObject(stringBuilder.toString());
        } else {
            Log.d("Post-Error", connection.getResponseMessage());
            return null;
        }
    } catch (Exception exception) {
        Log.e("Post-Exception", exception.toString());
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

联系人数据需要使用以下方法发送:

public static JSONObject registerTask(Context ctx, String sUrl, List<String> names, List<String> phoneNums) throws JSONException, IOException {
    JSONObject request = new JSONObject();

    request.putOpt("names", names);
    request.putOpt("phoneNums", phoneNums);

    sUrl = sUrl + "yourapiname";
    return post(sUrl, request.toString());
}

private static String sanitizeJSONBody(String body) {
    if (body.contains("password")) {
        body = body.replaceAll("\"password\":\"[^\"]+\"",
                "\"password\":******");
    }
    if (body.contains("newPassword")) {
        body = body.replaceAll("\"newPassword\":\"[^\"]+\"",
                "\"newPassword\":******");
    }

    return body;
}

你的PHP代码看起来像,

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$nameArray = array($input['names']);
$phoneNumArray = array($input['phoneNums']);
for($i=0;i<count($nameArray);$i++){
    $data = array(
        'name' => $nameArray[$i],
        'phone' => $phoneNumArray[$i],
    );
    $this->saveData('phonebook', $data);
}

答案 1 :(得分:2)

在PHP端,您需要以下JSON:

[
    {
        "name": "Chacha Kori",
        "phone": "+123456987"
    },
    {
        "name": "Gabuli Somi",
        "phone": "+123456987"
    },
    {
        "name": "Geto Somi",
        "phone": "+123456987"
    }
]

当您管理GsonBuilder为您提供此类JSON时(抱歉,无法帮助),您可以将其发布到您的PHP服务。

然后,在PHP中:

// Get the json variable which contains our JSON string
$json = $this->input->post('json');

// Decode JSON into PHP Array
$contacts = json_decode($json, true);

// Iterate through the collection of phone/names
foreach ($contacts as $row) {
    $data = array(
        'name' => $row['name'],
        'phone' => $row['phone'],
    );

    $this->saveData('phonebook', $data);
}

另请参阅:http://php.net/manual/en/function.json-decode.php