Skip to content

Instantly share code, notes, and snippets.

@zern3w
Created March 28, 2019 08:25
Show Gist options
  • Save zern3w/f9ff4adb9da1c5aeece1f9ebcd311501 to your computer and use it in GitHub Desktop.
Save zern3w/f9ff4adb9da1c5aeece1f9ebcd311501 to your computer and use it in GitHub Desktop.
package android.packcargo.com.myapplication.core;
import android.packcargo.com.myapplication.BuildConfig;
import android.packcargo.com.myapplication.core.constant.ServiceConstant;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
private static OkHttpClient.Builder httpClient;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(ServiceConstant.URL_SERVER)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}
public static <S> S createService(Class<S> serviceClass, final String token) {
if (httpClient == null) {
httpClient = new OkHttpClient.Builder();
if (token != null) {
httpClient.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
httpClient.connectTimeout(ServiceConstant.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(ServiceConstant.WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(ServiceConstant.READ_TIMEOUT, TimeUnit.SECONDS)
.addInterceptor(addLogging());
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static HttpLoggingInterceptor addLogging() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
if (BuildConfig.DEBUG) {
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
}
return logging;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment