Retrofit 2.0中onResponse内的条件逻辑无法正常运行
Hey there! Let’s dig into why your login POST request’s onResponse conditional logic isn’t behaving as expected. I’ve run into similar snags before, so let’s walk through the most common fixes step by step:
1. Don’t Mix Up HTTP Success with Business Logic Success
Retrofit’s response.isSuccessful() only checks if the HTTP status code falls in the 2xx range (like 200 OK). It doesn’t care if your backend returned a "login failed" message in the response body—this is the #1 mistake people make here!
You need to first validate the HTTP success, then check your backend’s custom success indicator (like a code field or isSuccess boolean). Here’s how to adjust your onResponse code:
@Override public void onResponse(Call<AuthResponse> call, Response<AuthResponse> response) { showProgress(false, ""); // First confirm the HTTP request itself succeeded if (response.isSuccessful()) { AuthResponse authResponse = response.body(); // Guard against null response body (even 2xx responses can be empty!) if (authResponse != null) { // Now check your backend's specific success condition if (authResponse.getCode() == 200 || authResponse.isSuccess()) { // Login success flow Toast.makeText(MainActivity.this, "Welcome back!", Toast.LENGTH_SHORT).show(); } else { // Backend says login failed (e.g., wrong password or username) Toast.makeText(MainActivity.this, authResponse.getMessage(), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Empty response from server", Toast.LENGTH_SHORT).show(); } } else { // Handle non-2xx HTTP errors (401 Unauthorized, 500 Server Error, etc.) try { String errorDetails = response.errorBody().string(); Toast.makeText(MainActivity.this, "Error: " + response.code() + " - " + errorDetails, Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "Error: " + response.code(), Toast.LENGTH_SHORT).show(); } } }
2. Double-Check Your AuthResponse Model Class
If your AuthResponse isn’t correctly deserialized from the backend’s JSON, all fields will be null or default values—making your conditionals fail silently. Verify:
- Field names match the JSON keys (use
@SerializedNameif they don’t, e.g., JSON usesstatusbut your field isisSuccess) - Nested objects (like a token payload) are properly modeled
- You’re using the right converter factory (Gson, Moshi, etc.) in your Retrofit setup
Example of a properly annotated model:
public class AuthResponse { @SerializedName("status_code") private int code; @SerializedName("message") private String message; @SerializedName("auth_token") private String token; // Getters public int getCode() { return code; } public String getMessage() { return message; } public String getToken() { return token; } }
3. Log the Full Request/Response
Add Retrofit’s logging interceptor to see exactly what’s being sent to the server and what’s coming back. This is invaluable for debugging mismatched JSON or unexpected responses.
Add the interceptor to your OkHttpClient:
OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY)) // Logs full request/response details .build(); // Attach to your Retrofit instance Retrofit retrofit = new Retrofit.Builder() .baseUrl("YOUR_BASE_URL") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build();
Check Logcat for the full request body (your username/password) and response body—this will tell you if the backend is returning what you expect.
4. Guard Against Null Pointers
Even if response.isSuccessful() is true, response.body() can still be null (e.g., server returns 204 No Content). Always add a null check before accessing fields in AuthResponse to avoid crashes that stop your logic from running.
5. Avoid Blocking the Main Thread
onResponse runs on the main thread, so if you’re doing heavy work (like parsing large data or disk operations) inside it, the UI might freeze or your logic might not execute properly. Keep onResponse focused on UI updates and light processing—move heavy tasks to a background thread if needed.
内容的提问来源于stack exchange,提问作者Matius Nugroho Aryanto

