Created
March 14, 2016 22:54
-
-
Save bhdrkn/d60ddca6a3a9ea2e994b to your computer and use it in GitHub Desktop.
Example Android Application with OkHTTP and Retrofit with Caching
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
import android.app.Application; | |
import android.util.Log; | |
import com.bahadirakin.service.UserService; | |
import com.bahadirakin.util.Constants; | |
import com.bahadirakin.util.LoggingInterceptor; | |
import com.bahadirakin.util.NetworkUtil; | |
import com.squareup.okhttp.Cache; | |
import com.squareup.okhttp.OkHttpClient; | |
import retrofit.RequestInterceptor; | |
import retrofit.RestAdapter; | |
import retrofit.client.OkClient; | |
import java.io.File; | |
import java.util.concurrent.Executor; | |
import java.util.concurrent.Executors; | |
public class MyApplication extends Application { | |
private UserService userService; | |
public void onCreate() { | |
initializeServices(); | |
} | |
private void initializeServices() { | |
Log.i("MyApplication", "TempDir: " + System.getProperty("java.io.tmodir")); | |
final File cacheDir = new File(System.getProperty("java.io.tmpdir"), "my.cache"); | |
Log.i("MyApplication", "CacheDirExists?: " + cacheDir.exists()); | |
final Cache cache = new Cache(cacheDir, 10 * 1024 * 1024); | |
final OkHttpClient okHttpClient = new OkHttpClient(); | |
okHttpClient.setCache(cache); | |
okHttpClient.networkInterceptors().add(new LoggingInterceptor()); | |
final Executor executor = Executors.newCachedThreadPool(); | |
final RestAdapter restAdapter = new RestAdapter.Builder() | |
.setExecutors(executor, executor) | |
.setEndpoint(Constants.SERVICE_BASE_URL) | |
.setClient(new OkClient(okHttpClient)) | |
.setRequestInterceptor(new RequestInterceptor() { | |
@Override | |
public void intercept(RequestFacade request) { | |
if (!NetworkUtil.isOnline(getApplicationContext())) { | |
int maxStale = 60 * 60 * 24 * 7; | |
request.addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale); | |
} | |
} | |
}) | |
.build(); | |
userService = restAdapter.create(UserService.class); | |
} | |
public UserService getUserService() { | |
return userService; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment