2
我正在使用Retrofit和OkHttp進行Android應用。爲特定呼叫設置超時時間
我跟着this tutorial創建一個類來處理API客戶端:
public class ApiClient {
public static final String API_BASE_URL = "https://www.website.com/api/";
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
private static Gson gson = new GsonBuilder()
.setLenient()
.create();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(API_URL);
private static Retrofit retrofit = builder.build();
private static HttpLoggingInterceptor logging =
new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY);
public static Retrofit getRetrofit() {
return retrofit;
}
public static <S> S createService(Class<S> serviceClass, Context context) {
if (!httpClient.interceptors().contains(logging)) {
httpClient.addInterceptor(logging);
}
builder.client(httpClient.build());
retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
這裏是我如何在客戶端調用我的應用程序的各個部分:
ApiInterface apiService = ApiClient.createService(ApiInterface.class, context);
Call<BasicResponse> call = apiService.uploadImage();
call.enqueue(new Callback<BasicResponse>() {
@Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
//
}
@Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
//
}
});
然而,我的應用程序具有圖像上傳功能,允許用戶將圖像上傳到服務器。 OkHttp的默認超時設置爲10-20秒之間的時間,這個時間不夠長,因爲如果圖片上傳時間過長,會導致超時錯誤。
因此,我想增加這個電話的超時時間爲。
我怎麼能在我的ApiClient
類添加一個方法來設置特定叫了暫停,並能夠做這樣的事情:
ApiInterface apiService = ApiClient.createService(ApiInterface.class, context);
// Add this
apiService.setTimeout(100 seconds);
Call<BasicResponse> call = apiService.uploadImage();
call.enqueue(new Callback<BasicResponse>() {
@Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
//
}
@Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
//
}
});
一旦我們實現了[更好的攔截器鏈](https://github.com/square/okhttp/issues/3039),即將發佈的版本會更簡單。 –