Last active
January 21, 2017 08:06
-
-
Save agustarc/8286b31cdec65c4c45db5edeeecf0017 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Module | |
public class SampleModule { | |
private static final int CONNECT_TIMEOUT = 15; | |
private static final int WRITE_TIMEOUT = 15; | |
private static final int READ_TIMEOUT = 15; | |
private static final String baseUrl; // your base url; | |
@Provides | |
@Singleton | |
Cache provideOkHttpCache(Application application) { | |
final int cacheSize = 10 * 1024 * 1024; // 10MB | |
return new Cache(application.getCacheDir(), cacheSize); | |
} | |
@Provides | |
@Singleton | |
Gson provideGson() { | |
return new GsonBuilder() | |
.registerTypeAdapterFactory(AutoValueGsonFactory.create()) | |
.create(); | |
} | |
@Provides | |
@Singleton | |
OkHttpClient provideOkHttpClient(Cache cache, AccountPreferences prefs) { | |
return new OkHttpClient.Builder() | |
.cache(cache) | |
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) | |
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) | |
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) | |
.addInterceptor(chain -> { | |
if (StringUtil.isNotEmpty(prefs.getToken())) { | |
final String bearer = "BEARER " + prefs.getToken(); | |
final Request.Builder builder = chain.request().newBuilder() | |
.header("Authorization", bearer) | |
.header("Accept", "application/json"); | |
return chain.proceed(builder.build()); | |
} else { | |
return chain.proceed(chain.request()); | |
} | |
}).build(); | |
} | |
@Provides | |
@Singleton | |
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { | |
return new Retrofit.Builder() | |
.addConverterFactory(GsonConverterFactory.create(gson)) | |
.baseUrl(baseUrl) | |
.client(okHttpClient) | |
.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment