Skip to content

Instantly share code, notes, and snippets.

@ponnamkarthik
Created January 13, 2018 10:17
Show Gist options
  • Save ponnamkarthik/751aa6ce0544b3037763e8a09e558122 to your computer and use it in GitHub Desktop.
Save ponnamkarthik/751aa6ce0544b3037763e8a09e558122 to your computer and use it in GitHub Desktop.
HTTP Utility using retrofit2 and okhttp
private void prepareNetwork() {
File httpCacheDirectory = new File(getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.build();
Retrofit signUp = new Retrofit.Builder()
.client(client)
.baseUrl(getString(R.string.base_url))
.addConverterFactory(GsonConverterFactory.create())
.build();
api = signUp.create(Api.class);
}
private void getData() {
Call<ResponseBody> call = api.getData(user.getUid());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
String response = response.body().string();
} catch (Exception e) {
showError();
}
}
@Override
public void onFailure(Call<List<DashboardModel>> call, Throwable t) {
t.printStackTrace();
}
});
}
private final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response originalResponse = chain.proceed(chain.request());
if (Network.hasConnectivity(Dashboard.this, true)) {
int maxAge = 60; // read from cache for 1 minute
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
}
};
private void startDataService() {
prepareNetwork();
getData();
}
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface Api {
@GET("data")
Call<ResponseBody> getData(@Query("id") String id);
}
...
dependencies {
...
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
...
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment