乐闻世界logo
搜索文章和话题

How to send a JSON object over Request with Android?

1个答案

1

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

  1. Add dependencies: First, to use Retrofit, you need to add the Retrofit dependency to your Android project's build.gradle file.

    gradle
    implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    Here, the converter-gson dependency is also added because we need to use GSON for handling JSON.

  2. Create a Java interface: Create an interface to define HTTP requests. Suppose we need to send a JSON object to create a new user:

    java
    import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface ApiService { @POST("users/new") Call<UserResponse> createUser(@Body User user); }

    Here, the @Body annotation indicates that the entire User object is sent as the request body.

  3. Define POJO classes: Define a simple POJO class to represent the user and response. For example:

    java
    public 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 }
  4. Create Retrofit instance and send request: Next, you need to create a Retrofit instance and use it to send requests.

    java
    import 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:

    java
    Retrofit 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.

2024年8月9日 02:40 回复

你的答案