Skip to content

Instantly share code, notes, and snippets.

@danySam
Created February 21, 2019 22:52
Show Gist options
  • Save danySam/0c1104a36b06807b69e96d48ea09c413 to your computer and use it in GitHub Desktop.
Save danySam/0c1104a36b06807b69e96d48ea09c413 to your computer and use it in GitHub Desktop.
Retrofit Connection Manager Boilerplate
package com.newecon.qounter.connection;
import ?.API;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Danny on 10-09-2017.
*/
public class ConnectionManager {
private static final ConnectionManager conManager = new ConnectionManager();
private static API client;
private static Retrofit retrofit;
private static final String BASE_URL = "https://api.danysam.net";
public static ConnectionManager getInstance() {
return conManager;
}
private ConnectionManager() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request baseRequest = chain.request();
Request headerRequest = baseRequest.newBuilder()
.header("Content-Type", "application/json")
.method(baseRequest.method(), baseRequest.body())
.build();
return chain.proceed(headerRequest);
}
});
// add logging as last interceptor
httpClient.addInterceptor(logging);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build());
retrofit = builder.build();
client = retrofit.create(API.class);
}
public API getClient() {
return client;
}
public Retrofit getRetrofit() {
return retrofit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment