Android中Retrofit请求无响应无错误,enqueue未进入回调问题排查
Let's break down the key issues stopping your Retrofit call from hitting onResponse or onFailure, and fix them step by step:
1. Your OkHttpClient Timeout Settings Aren't Being Applied
You're building the OkHttpClient before setting your timeout values — that means the client passed to Retrofit has no timeout config at all, and if the request hangs, it might never trigger a callback.
Here's the corrected order for configuring your client:
public void getCheapestFromToSpain() { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); // Set timeouts FIRST, then build the client httpClient.connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES); Retrofit retrofit = new Retrofit.Builder() .baseUrl(urlGetCheapest) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient.build()) // Use the already-configured builder .build(); // ... rest of your code (date formatting, creating the call, etc.) }
2. Base URL and @GET Path Conflict
Retrofit has strict rules for combining base URLs and endpoint paths:
- Your base URL must end with a trailing
/(yours does:https://services-api.ryanair.com/farfnd/3/) - Your
@GETpath must not start with a leading/— otherwise, Retrofit will ignore the base URL's path and jump straight to the domain.
Your current @GET("/oneWayFares") is making a request to https://services-api.ryanair.com/oneWayFares instead of the correct https://services-api.ryanair.com/farfnd/3/oneWayFares. Fix the Controller interface:
public interface Controller { @GET("oneWayFares") // Remove the leading slash Call<GetCheapestResponseType> getCheapest( @Query("departureAirportIataCode") String departureAirportIataCode, @Query("outboundDepartureDateFrom") String outboundDepartureDateFrom, @Query("outboundDepartureDateTo") String outboundDepartureDateTo); }
3. Extra Checks to Guarantee Callbacks Fire
- Add Internet Permission (if this is an Android project): Make sure your
AndroidManifest.xmlincludes:<uses-permission android:name="android.permission.INTERNET" /> - Verify Your Response Model: Double-check that
GetCheapestResponseTypematches the JSON structure returned by the Ryanair API. Mismatched fields or missing Gson annotations could cause silent parsing failures. - Add Logging for Debugging: Use OkHttp's logging interceptor to see exactly what's being sent/received. Add this to your OkHttpClient builder:
This will print full request/response details in your logcat, making it easy to spot URL issues, missing parameters, or API errors.HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(logging);
After fixing these two main issues, your Retrofit call should start triggering the callbacks as expected.
内容的提问来源于stack exchange,提问作者janusz j

