2017-05-27 73 views
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) { 
     // 
    } 
}); 

回答

1

据我可以告诉这似乎只用成为可能创建两个单独的Retrofit服务,并使用两个不同的OkHttp实例。一个实例会有默认超时,一个会配置扩展超时。

+1

一旦我们实现了[更好的拦截器链](https://github.com/square/okhttp/issues/3039),即将发布的版本会更简单。 –