如何使用RxJava与Retrofit向服务端发送JSON参数?
Great to see you already have Retrofit configured with Gson and RxJava2 adapters—half the work is done! Here's how to extend this setup to send JSON parameters to your server:
1. Create a Request Model Class
First, define a plain old Java object (POJO) that mirrors the JSON structure your server expects. Gson will automatically serialize this into JSON when you send the request.
For example, if your server expects a JSON payload like this:
{ "username": "john_doe", "email": "john@example.com", "age": 30 }
Your model class would look like this:
public class UserRequest { private String username; private String email; private int age; // Constructor for easy object creation public UserRequest(String username, String email, int age) { this.username = username; this.email = email; this.age = age; } // Getters are optional (Gson can serialize private fields directly) public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } }
2. Define Your Retrofit API Interface
Next, create an interface that declares your API endpoint. Use RxJava's Observable (or Single for one-time success/failure responses) as the return type, and annotate the request body with @Body:
import io.reactivex.Observable; import retrofit2.http.Body; import retrofit2.http.POST; public interface ApiService { // Replace "/users/create" with your actual endpoint path @POST("/users/create") Observable<UserResponse> createUser(@Body UserRequest userRequest); }
(Note: UserResponse is another POJO that matches the JSON structure your server returns—create this similarly to UserRequest to parse the response.)
3. Initialize the API Service
Use your existing provideRetrofit method to create an instance of ApiService:
// Example initialization (place this in your repository or dependency injection setup) ApiService apiService = provideRetrofit(okHttpClient).create(ApiService.class);
4. Execute the Request with RxJava
Now you can use the apiService to send the JSON request. Remember to handle threading properly—run network calls on a background thread and observe results on the main thread if updating UI:
// Create your request object UserRequest request = new UserRequest("john_doe", "john@example.com", 30); // Execute the call with RxJava apiService.createUser(request) .subscribeOn(Schedulers.io()) // Run network operation on background thread .observeOn(AndroidSchedulers.mainThread()) // Observe results on main thread (for Android) .subscribe( userResponse -> { // Handle successful response Log.d("API Success", "User ID: " + userResponse.getUserId()); }, throwable -> { // Handle error cases (network issues, server errors, etc.) Log.e("API Error", "Failed to create user", throwable); } );
5. Verify Your Logging Interceptor (Optional)
Since you're using HttpLoggingInterceptor, make sure you set it to log the request body to confirm your JSON is being sent correctly:
// Complete your OkHttpClient setup public OkHttpClient client(HttpLoggingInterceptor loggingInterceptor, Cache cache) { // Set logging level to BODY to see full request/response details loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .cache(cache) .addInterceptor(loggingInterceptor) // Add other interceptors (like auth headers) if needed .build(); }
That's all! Your existing Retrofit setup already includes GsonConverterFactory, which handles converting the POJO to JSON automatically. The RxJava call adapter lets you use reactive observables to handle the response asynchronously.
内容的提问来源于stack exchange,提问作者Cyrus the Great

