如何通过GSON将手机联系人以JSON格式发送至服务器
Hey there! You're already halfway there with your contact retrieval code and GSON setup—let's tie it all together to send that JSON to your server. Here's a step-by-step guide to get it working:
First, Fix the Timing Issue in Your Current Code
Right now, you're converting arrayList to JSON in onCreate(), but at that point, the list is still empty because contact retrieval happens asynchronously (after permission is granted). You need to move the GSON conversion and network call after you've populated the arrayList with contacts.
Update your gettingPhoneContacts() method to trigger the send operation once contacts are loaded:
private void gettingPhoneContacts() { ContentResolver cr = getApplicationContext().getContentResolver(); Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.RawContacts.ACCOUNT_TYPE}, ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ", null, null); if (c.getCount() <= 0) { Toast.makeText(getApplicationContext(), "No Phone Contact Found..!", Toast.LENGTH_SHORT).show(); return; } arrayList.clear(); // Clear old data before adding new contacts while (c.moveToNext()) { String Phone_number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); arrayList.add(new Contact_Pojo(name, Phone_number)); Log.d("contactsss", Phone_number + " " + name); } c.close(); // Don't forget to close the cursor! // Now that contacts are loaded, convert to JSON and send to server sendContactsToServer(); }
Add Network Library Dependency (OkHttp)
We'll use OkHttp for reliable network calls—add this to your app-level build.gradle (Module level) dependencies:
dependencies { // ... your existing dependencies implementation 'com.squareup.okhttp3:okhttp:4.12.0' implementation 'com.google.code.gson:gson:2.10.1' }
Don't forget to add the INTERNET permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Create the Method to Send JSON to Server
Add this method to your Access_contacts class. It converts the contact list to JSON, then sends it via a POST request to your server endpoint:
private void sendContactsToServer() { // Convert contact list to JSON Gson gson = new Gson(); Type contactListType = new TypeToken<List<Contact_Pojo>>() {}.getType(); String jsonContacts = gson.toJson(arrayList, contactListType); // Define your server endpoint URL String serverUrl = "https://your-server-endpoint.com/contacts"; // Build the request OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(jsonContacts, MediaType.parse("application/json; charset=utf-8")); Request request = new Request.Builder() .url(serverUrl) .post(body) .build(); // Execute the request asynchronously (don't run network calls on main thread!) client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Handle network failure (run UI updates on main thread) runOnUiThread(() -> { Toast.makeText(Access_contacts.this, "Failed to send contacts: " + e.getMessage(), Toast.LENGTH_LONG).show(); Log.e("NetworkError", e.getMessage()); }); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { // Handle successful response runOnUiThread(() -> { Toast.makeText(Access_contacts.this, "Contacts sent successfully!", Toast.LENGTH_SHORT).show(); }); String responseBody = response.body().string(); Log.d("ServerResponse", responseBody); } else { // Handle server error runOnUiThread(() -> { Toast.makeText(Access_contacts.this, "Server error: " + response.code(), Toast.LENGTH_LONG).show(); }); Log.e("ServerError", "Code: " + response.code() + ", Message: " + response.message()); } } }); }
Key Notes to Remember
- Never run network calls on the main thread: OkHttp's
enqueue()handles this by running the request on a background thread, and we userunOnUiThread()to update UI elements (like Toasts) from the callback. - Handle edge cases: What if the device has no internet? What if the server returns an error? The code above includes basic error handling, but you can expand it based on your needs.
- Clean up resources: Always close cursors after using them (we added
c.close()ingettingPhoneContacts()to prevent memory leaks). - Test with a real server: Replace
https://your-server-endpoint.com/contactswith your actual server URL that accepts POST requests with JSON body.
内容的提问来源于stack exchange,提问作者Tapesh Gupta

