2017-05-27 2 views
2

私はAndroidアプリにRetrofitとOkHttpを使用しています。特定のコールのタイムアウトを設定する

私はAPIクライアントを処理するためのクラスを作成するthis tutorialを追っ:

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

にのみによって可能であると思われます異なる2つのRetrofitサービスを作成し、2つの異なるOkHttpインスタンスを作成します。 1つのインスタンスはデフォルトのタイムアウトを持ち、1つは拡張タイムアウトを構成します。

+1

[より良いインターセプタチェーン](https://github.com/square/okhttp/issues/3039)を実装すると、今後のリリースでさらに簡単になります。 –

関連する問題