java - 将 JSONArray 发布到 php

标签 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);
            }
        }

有什么建议吗?

最佳答案

我的建议是不要使用 NameValuePair,因为在 Lollipop 版本之上,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);
}

关于java - 将 JSONArray 发布到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41055056/

相关文章:

java - 在 Java 中定义一个固定大小的列表

java - 如何编写 ETL 以根据 Oracle UNDO 设置进行操作?

java - Maven 正在尝试从不同目标的中心下载父 pom

android - 如何在 android 中使用 Intent 打开前置摄像头?

java - Android编程: ANDROID_CONTEXT parameter is not passed in error

java - javadoc可以嵌套吗?

java - 什么时候调用 onSaveInstanceState() 方法?

android - 如何从 Intent 启动 ListActivity?

java - 从 Firestore 集合中检索文档 ID (Android)

java - 我们如何在 Android 中将评级栏星星图标更改为其他图标?