In Android development, sending JSON objects is a common method for communicating with network servers. Here, I will demonstrate how to use a popular HTTP library—Retrofit—to implement sending JSON objects.
Sending JSON Objects with Retrofit
-
Add dependencies: First, to use Retrofit, you need to add the Retrofit dependency to your Android project's
build.gradlefile.gradleimplementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'Here, the
converter-gsondependency is also added because we need to use GSON for handling JSON. -
Create a Java interface: Create an interface to define HTTP requests. Suppose we need to send a JSON object to create a new user:
javaimport retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface ApiService { @POST("users/new") Call<UserResponse> createUser(@Body User user); }Here, the
@Bodyannotation indicates that the entireUserobject is sent as the request body. -
Define POJO classes: Define a simple POJO class to represent the user and response. For example:
javapublic class User { private String name; private int age; // Constructors, getters, and setters } public class UserResponse { private boolean success; private String message; // Constructors, getters, and setters } -
Create Retrofit instance and send request: Next, you need to create a Retrofit instance and use it to send requests.
javaimport retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }Then use this client to send requests:
javaRetrofit retrofit = RetrofitClient.getClient("https://api.example.com/"); ApiService service = retrofit.create(ApiService.class); User newUser = new User("Zhang San", 25); Call<UserResponse> call = service.createUser(newUser); call.enqueue(new Callback<UserResponse>() { @Override public void onResponse(Call<UserResponse> call, Response<UserResponse> response) { if (response.isSuccessful()) { Log.d("TAG", "onResponse: Success"); } else { Log.d("TAG", "onResponse: Error " + response.code()); } } @Override public void onFailure(Call<UserResponse> call, Throwable t) { Log.e("TAG", "onFailure: " + t.getMessage()); } });
Summary
Through the above steps, you can use the Retrofit library in your Android project to send JSON objects. This method not only has a clear code structure but also, through Retrofit's encapsulation, makes network requests more concise and easier to manage.