polish OkHttp plugin
package io.freefair.gradle.plugins.okhttp;
-import okhttp3.CacheControl;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
+import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
+import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import java.io.IOException;
/**
* @author Lars Grefer
@@ -28,25 +28,33 @@ public class OkHttpPlugin implements Plugin<Project> {
public OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
+
+ OkHttpClient.Builder builder = new OkHttpClient.Builder()
+ .cache(okHttpCachePlugin.getCache());
+
+ if (project.getGradle().getStartParameter().isOffline()) {
+ builder = builder.addInterceptor(new ForceCacheInterceptor());
+ }
+
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(project.getLogger()::info);
loggingInterceptor.level(HttpLoggingInterceptor.Level.BASIC);
+ builder = builder.addInterceptor(loggingInterceptor);
- okHttpClient = new OkHttpClient.Builder()
- .addInterceptor(chain -> {
- Request request = chain.request();
+ okHttpClient = builder.build();
+ }
+ return okHttpClient;
+ }
- if (project.getGradle().getStartParameter().isOffline()) {
- request = request.newBuilder()
+ private static class ForceCacheInterceptor implements Interceptor {
+ @Nonnull
+ @Override
+ public Response intercept(@Nonnull Chain chain) throws IOException {
+ Request newRequest = chain.request()
+ .newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
- }
- return chain.proceed(request);
- })
- .addInterceptor(loggingInterceptor)
- .cache(okHttpCachePlugin.getCache())
- .build();
+ return chain.proceed(newRequest);
}
- return okHttpClient;
}
}
