我正在为我的Android应用程序使用Retrofit和OkHttp。
我跟着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) {
//
}
});
答案 0 :(得分:1)
据我所知,这似乎只能通过创建两个单独的Retrofit服务来实现,其中包含两个不同的OkHttp
个实例。一个实例将具有默认超时,一个将配置扩展超时。