You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit注册成功但onResponse未调用、onFailure触发问题求助

Troubleshooting Retrofit onFailure Triggered Despite Successful Registration

Hey there, let's break down why your Retrofit call is hitting onFailure() even though the registration completes successfully on the server—and why Call.isExecuted() returns true (which confirms the request was sent out). Here are the most common culprits and actionable steps to fix this:

1. Response Parsing Failures (Most Likely)

Retrofit will trigger onFailure() if it can't parse the server's response into your Model class. This happens even if the server says the registration succeeded. Common issues here include:

  • Mismatched field names (e.g., server returns user_id but your Model uses userId without the @SerializedName annotation)
  • Incorrect data types (e.g., server returns a String for age but your Model uses an int)
  • Missing required fields that the server doesn't return (if your Model has non-null fields without default values)

Fix Steps:

  • Print the raw server response to verify its structure. Add this to your onFailure() method if the error is an HttpException:
    @Override
    public void onFailure(Call<RegistrationResponse> call, Throwable t) {
        t.printStackTrace();
        if (t instanceof HttpException) {
            HttpException httpEx = (HttpException) t;
            try {
                String rawResponse = httpEx.response().errorBody().string();
                Log.d("RetrofitDebug", "Raw server response: " + rawResponse);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  • Double-check your Model class's @SerializedName annotations match the server's JSON keys exactly. For example:
    public class RegistrationResponse {
        @SerializedName("user_id") // Match server's key exactly
        private int userId;
        @SerializedName("success_message")
        private String successMessage;
    
        // Add getters/setters or use Lombok for brevity
    }
    

2. Non-2xx HTTP Status Code

Retrofit only considers responses with 2xx status codes (like 200 OK, 201 Created) as successful. If your server returns a 3xx, 4xx, or 5xx code even after successful registration, Retrofit will trigger onFailure().

Fix Steps:

  • Check the status code in onFailure() using the snippet above (look for httpEx.code()). If it's a non-2xx code, either:
    • Adjust your server to return a 2xx code for successful registrations
    • Or modify your Retrofit setup to handle non-2xx codes as successful (using a custom interceptor or response handler)

3. Network Interruption Mid-Response

Even though the request was sent (isExecuted() = true), a network drop or timeout while receiving the response can cause Retrofit to fire onFailure(). Look for SocketTimeoutException or ConnectException in the Throwable stack trace.

Fix Steps:

  • Increase OkHttpClient timeout settings if timeouts are the issue:
    OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .build();
    
  • Test the flow on a stable network to rule out intermittent connectivity issues.

4. Misconfigured Retrofit Setup

If you forgot to add a converter factory (like GsonConverterFactory) or used an incompatible version, Retrofit can't parse the response and will fail.

Fix Steps:

  • Ensure your Retrofit builder includes a converter factory for your response format (JSON is most common):
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("YOUR_BASE_URL")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
    

Final Tip

Start by logging the full error details in onFailure()—this will immediately point you to the root cause. Once you have that info, fixing the issue becomes straightforward.

内容的提问来源于stack exchange,提问作者Milan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:58:26