Skip to content

Instantly share code, notes, and snippets.

@CoderJava
Last active September 25, 2018 16:33
Show Gist options
  • Select an option

  • Save CoderJava/62323bcf4c237c26664d3e2a7c65df13 to your computer and use it in GitHub Desktop.

Select an option

Save CoderJava/62323bcf4c237c26664d3e2a7c65df13 to your computer and use it in GitHub Desktop.
Example Singleton RetrofitClient with Authorization
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private final String baseUrl = "www.google.com";
private static RetrofitClient instance;
private static Retrofit retrofit;
private Context context;
public RetrofitClient(Context context) {
this.context = context;
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
CachingControlInterceptor cachingControlInterceptor = new CachingControlInterceptor();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(cachingControlInterceptor)
.addNetworkInterceptor(httpLoggingInterceptor)
.build();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLenient();
Gson gson = gsonBuilder.create();
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static synchronized RetrofitClient getInstance(Context context) {
if (instance == null) {
instance = new RetrofitClient(context);
}
return instance;
}
class CachingControlInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
SharedPreferences sharedPreferences = context.getSharedPreferences("PREF_TOKEN", Context.MODE_PRIVATE);
String token = sharedPreferences.getString("key_token", null);
Request request = chain.request();
if (token != null) {
try {
request.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new JSONObject().put("token", token).toString()));
} catch (JSONException e) {
e.printStackTrace();
}
}
return chain.proceed(request).newBuilder().build();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment