Listen to all responses globally? - android

If a user is banned on my app, my server returns the following response:
return response()->json([
'banned' => 'You are banned.'
], 403);
So whenever a Retrofit request is made to the server, I need to be able to globally check and read all responses in case the user has been banned.
Here is my ApiClient.java that handles Retrofit:
public class ApiClient {
public static final String API_URL = "http://www.website.com/api/";
private static int defaultTimeout = 30;
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
private static Gson gson = new GsonBuilder()
.setLenient()
.create();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(API_URL);
private static Retrofit retrofit = builder.build();
public static Retrofit getRetrofit() {
return retrofit;
}
public static <S> S createService(Class<S> serviceClass, Context context) {
return createService(serviceClass, context, null);
}
public static <S> S createService(Class<S> serviceClass, Context context, final String authToken) {
return createService(serviceClass, context, authToken, defaultTimeout);
}
public static <S> S createService(Class<S> serviceClass, Context context, final String authToken, int timeout) {
if (authToken != null) {
TokenInterceptor tokenInterceptor = new TokenInterceptor(authToken);
if (!httpClient.interceptors().contains(tokenInterceptor)) {
httpClient.addInterceptor(tokenInterceptor);
}
TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(context, authToken);
httpClient.authenticator(tokenAuthenticator);
}
httpClient.connectTimeout(timeout, TimeUnit.SECONDS);
httpClient.writeTimeout(timeout, TimeUnit.SECONDS);
httpClient.readTimeout(timeout, TimeUnit.SECONDS);
builder.client(httpClient.build());
retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
How can I modify this so that it checks every response from my server to check if the user has been banned? Would I create an interceptor in this case? How?

Yeah just create an interceptor that looks for 403 responses.
public class BannedInterceptor implements Interceptor {
#Override
public Response intercept(#NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == 403) {
throw new IOException("user banned!");
}
return response;
}
}
And add it to your OkHttp client.
httpClient.addInterceptor(new BannedInterceptor())

Related

Unauthorized when send POST method

I have a problem with Retrofit and post method.
My GET method with authentication work but POST isn't working.
I logged without any problems, and do any GET method.
When I am trying send some data to REST API (Spring) I get this error:
Response{protocol=http/1.1, code=401, message=, url=http://10.101.12.31:8080/add}
My Code:
DataAPI.java:
public class DataAPI {
private static final String BASE_URL = "http://10.101.12.31:8080/";
static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(
Class<S> serviceClass, String username, String password) {
if (!TextUtils.isEmpty(username)
&& !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createService(serviceClass, authToken);
}
return createService(serviceClass, null);
}
public static <S> S createService(
Class<S> serviceClass, final String authToken) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor =
new AuthenticationInterceptor(authToken);
if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
public static DepartmentService getDepartmentService() {
return retrofit.create(DepartmentService.class);
}
}
AuthenticationInterceptor.java:
public class AuthenticationInterceptor implements Interceptor {
private String authToken;
public AuthenticationInterceptor(String token) {
this.authToken = token;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.addHeader("Authorization", authToken);
Request request = builder.build();
return chain.proceed(request);
}
}
Web interface:
public interface Service {
#POST("/add")
Call<Void> addUser(#Body User user);
}
Method:
public void buttonOne(View v) {
DataAPI.createService(Service.class, getIntent().getStringExtra("authToken"))
.addUser(user)).enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
System.out.println(response);
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_SHORT).show();
}
});
}

Retrofit Logging Error

I am authenticating against an API EndPoint using the Password Grant Flow for OAuth2. The library I am using is Retrofit.
I get the following error:
D/OkHttp: {"error":"invalid_clientId","error_description":"ClientId should be sent."}
I would like to see exactly what API Call I am sending so I can check it for errors.. I have searched the web and found that you need to add a LoggingInterceptor, which I am doing. Still not getting the full API Call..
In my log I get a track of the headers I am sending, as well as the URL, but not the body parameters.. Is there a way to also get the body parameters in the logging?
I would like to see each parameter with its sent value..
The code with provisional credentials can be found at:
https://github.com/NVwingh84/ATTAPITest
Code that I am using is:
public class MainActivity extends AppCompatActivity {
private String grant_type = "password";
private String username = "xxxxx";
private String password = "xxxxx";
private String clientId = "xxxxx";
private String client_secret = "xxxxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AccessTokenRequest mytokenrequest = new AccessTokenRequest(grant_type,username,password,clientId,client_secret);
sendNetworkRequest(mytokenrequest);
}
public void sendNetworkRequest(AccessTokenRequest accessTokenRequest){
//create okhttpclientbuilder and set up logging for full logging level "Body"
OkHttpClient.Builder okhttpclientbuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//App will only log if you are in development mode
if (BuildConfig.DEBUG){
okhttpclientbuilder.addInterceptor(loggingInterceptor);
}
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://api.allthingstalk.io")
.addConverterFactory(GsonConverterFactory.create())
.client(okhttpclientbuilder.build());
Retrofit retrofit = builder.build();
AccessTokenClient client = retrofit.create(AccessTokenClient.class);
Call<AccessTokenRequest> call = client.getAccessToken();
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Toast.makeText(MainActivity.this, "EndPoint Response", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
};
}
Try this code.
add below dependency into app level gradle file..
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
and make separate class for retrofit object define and it is easy to access like below code..
public class ApiClient {
private final static String BASE_URL = "https://dog.ceo/api/breed/";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}

Is it possible to use multiple baseurl in retrofit?

I want to use two server url using retrofit, but only one is working when I am using two base url. Please tell me how to use two base url in android.
public class APIUtils {
public static String Url1 = "http://10.0.13.46:19460";
public static String Url12 = "http://freshcamera.herokuapp.com";
public static SOService getSOService(String url) {
return RetrofitClient.getClient(url1).create(SOService.class);
}
}
SOService class
public interface SOService {
//URL 2
#FormUrlEncoded
#POST("/api/user/LoginUser")
Call<Login> Login(#Field("username") String username, #Field("password")String password, #Field("grant_type")String passwords);
}
SOService_AI class
public interface SOService_AI {
//URL 1
#FormUrlEncoded
#POST("/finalresult1")
Call<List<AIImageProcessing>> AiImageCheck(#Field("img_data") String imgdata, #Field("name")String imgName);
}
I guess what you need is changing URL at runtime to a completely different one.
For example, the following code will override the URL passed as baseUrl to retrofit object.
#GET
public Call<ResponseBody> profilePicture(#Url String url);
Note: You can't add url param to #GET and #POST. The URL must be passed to #Url.
// ERROR ( #Url cannot be used with #GET URL)
#GET("users") // or POST
public Call<Foo> getUsers(#Url String url);
// CORRECT
#GET
public Call<Foo> getUsers(#Url String fullUrl);
Checkout this tutorial for further information.
if you are working two url then you create two retrofit object. because single retrofit object work on single url.
if you want to access two your make two retofit object like below code..
public class ApiClient {
private final static String BASE_URL = "https://simplifiedcoding.net/demos/";
private final static String BASE_URL2 = "http://freshcamera.herokuapp.com";
public static ApiClient apiClient;
private Retrofit retrofit = null;
private Retrofit retrofit2=null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
public Retrofit getClient2() {
return getClient2(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
private Retrofit getClient2(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL2)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
then after access like below code ..
ApiClient.getInstance().getClient();
ApiClient.getInstance().getClient2();
with Kotlin its even easier
companion object {
// init Retrofit base server instance
val redditClient by lazy { ApiService.invoke(REDDIT_BASE_URL) }
val stackClient by lazy { ApiService.invoke(STACK_BASE_URL) }
private val loggingInterceptor = HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
operator fun invoke(baseUrl: String): ApiService {
val client = OkHttpClient.Builder().apply {
/**addNetworkInterceptor(StethoInterceptor()) */
addNetworkInterceptor(loggingInterceptor)
connectTimeout(10, TimeUnit.MINUTES)
readTimeout(10, TimeUnit.MINUTES)
writeTimeout(10, TimeUnit.MINUTES)
}.build()
return Retrofit.Builder()
.client(client)
.baseUrl(baseUrl)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
}
}
just pass the baseUrl in the invoke method
This is really easy now
Simply use Post or Get without a constant url instead accept it in a parameter and annotate that parameter with #Url
#GET
suspend fun handshakeUser(#Url url : String): Response<JsonObject>
#POST
suspend fun makePostRequest(
#Header("Authorization") token: String = getToken(),
#Url url: String,
#Body inputModel: JsonObject
): Response<JsonObject>

How i pass token from java class to retrofit APIClient

I am using retrofit library for parsing data from json.But now i required to pass token in my request. I have set token in one Global class.Now i want to use that token in APIClient.But when i pass , it through null.
This is my APIClient
public class APIClient {
public static final String BASE_URL = "http://kartpays.bizs/api/v5/";
private static Retrofit retrofit = null;
public static final String FOLLOW_URL ="http://kartpays.biz/api/v1/follow/";
public static Retrofit getRetrofitInstance() {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request request = originalRequest.newBuilder()
.header("token", **I want to pass token here**)
.header("Content-Type", "application/json")
.method(originalRequest.method(), originalRequest.body())
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
retrofit = new Retrofit.Builder()
.baseUrl(FOLLOW_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
In this class i stored token
public class LibFile {
Context context;
public static SharedPreferences settings;
private static LibFile instance;
public static LibFile getInstance(Context context) {
if (instance == null) {
instance = new LibFile(context);
}
return instance;
}
public LibFile(Context context) {
this.context = context;
settings = context.getSharedPreferences(AppConstants.PREFS_FILE_NAME_PARAM, 0);
}
public String getUser_id() {
return settings.getString("user_id", "");
}
public void setUser_id(String link) {
settings.edit().putString("user_id", link).commit(); //get link from here
}
public String getToken() {
return settings.getString("token","");//pass key here
}
public static void setToken(String userName) {
settings.edit().putString("token", userName).commit();//get key from here
}
public void clearCache() {
settings.edit().clear().commit();
settings.edit().remove("link").commit();
}
}
Please Suggest me how to pass token dynamically. I could not pass static token because it changes continuously.Thanks in advance
If your token is stored in SharedPreference then check out below changes of your code,
public static Retrofit getRetrofitInstance(Context mContext) {
SharedPreferences settings = mContext.getSharedPreferences(AppConstants.PREFS_FILE_NAME_PARAM, 0);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request request = originalRequest.newBuilder()
.header("token", settings.getString("token", ""))
.header("Content-Type", "application/json")
.method(originalRequest.method(), originalRequest.body())
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
retrofit = new Retrofit.Builder()
.baseUrl(FOLLOW_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
A better solution suiting your code would be:
Request request = originalRequest.newBuilder()
.header("token", LibFile.getInstance(mContext).getToken())
.header("Content-Type", "application/json")
.method(originalRequest.method(), originalRequest.body())
.build();
Check this line: .header("token", LibFile.getInstance(mContext).getToken())
Which take an instance from the LibFile and gets a token.
In your http request, the header key should be "Authorization" instead of "token".
Request request = originalRequest.newBuilder()
.header("Authorization", **I want to pass token here**)
.header("Content-Type", "application/json")
.method(originalRequest.method(), originalRequest.body())
.build();
You can use below methods to put and get token from shared preferences.
public static boolean setStringPreference(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null && !TextUtils.isEmpty(key)) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
return editor.commit();
}
return false;
}
public static String getStringPreference(String key) {
String value = null;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
value = preferences.getString(key, null);
}
return value;
}

Retrofit and OkHttp basic authentication

I am trying to add basic authentication (username and password) to a Retrofit OkHttp client. This is the code I have so far:
private static Retrofit createMMSATService(String baseUrl, String user, String pass) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
I am using Retrofit 2.2 and this tutorial suggests using AuthenticationInterceptor, but this class is not available.
Where is the correct place to add the credentials? Do I have to add them to my interceptor, client or Retrofit object? And how do I do that?
Find the Solution
1.Write a Interceptor class
import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class BasicAuthInterceptor implements Interceptor {
private String credentials;
public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}
2.Finally, add the interceptor to an OkHttp client
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.build();
Retrofit 2
public class ServiceGenerator {
public static final String API_BASE_URL = "https://your.api-base.url";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(
Class<S> serviceClass, String username, String password) {
if (!TextUtils.isEmpty(username)
&& !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createService(serviceClass, authToken);
}
return createService(serviceClass, null);
}
public static <S> S createService(
Class<S> serviceClass, final String authToken) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor =
new AuthenticationInterceptor(authToken);
if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
}
Retrofit 1.9
public class ServiceGenerator {
public static final String API_BASE_URL = "https://your.api-base.url";
private static RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setClient(new OkClient(new OkHttpClient()));
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(Class<S> serviceClass, String username, String password) {
if (username != null && password != null) {
// concatenate username and password with colon for authentication
String credentials = username + ":" + password;
// create Base64 encodet string
final String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", basic);
request.addHeader("Accept", "application/json");
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
AuthenticationInterceptor.java
public class AuthenticationInterceptor implements Interceptor {
private String authToken;
public AuthenticationInterceptor(String token) {
this.authToken = token;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Authorization", authToken);
Request request = builder.build();
return chain.proceed(request);
}
}
Usage
Retrofit 2
Interface
public interface LoginService {
#POST("/login")
Call<User> basicLogin();
}
Requester
LoginService loginService =
ServiceGenerator.createService(LoginService.class, "user", "secretpassword");
Call<User> call = loginService.basicLogin();
call.enqueue(new Callback<User >() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
// user object available
} else {
// error response, no access to resource?
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
// something went completely south (like no internet connection)
Log.d("Error", t.getMessage());
}
}
Retrofit 1.9
Interface
public interface LoginService {
#POST("/login")
void basicLogin(Callback<User> cb);
}
Requester
LoginService loginService =
ServiceGenerator.createService(LoginService.class, "user", "secretpassword");
loginService.basicLogin(new Callback<User>() {
#Override
public void success(User user, Response response) {
// user object available
}
#Override
public void failure(RetrofitError error) {
// handle errors, too
}
});
More information see here.
add header interceptor
public class HeaderInterceptor implements Interceptor {
private PreferencesRepository mPrefs;
private String mAuth;
public HeaderInterceptor(PreferencesRepository p) {
mPrefs = p;
}
#Override
public Response intercept(Chain chain) throws IOException {
mAuth = (mPrefs.getAuthToken() != null)?mPrefs.getAuthToken():"";
Request r = chain.request()
.newBuilder()
.addHeader("Accept", "application/json")
// authorization token here
.addHeader("Authorization", "Bearer" + mAuth)
.build();
return chain.proceed(r);
}
}
add cacheinterceptor (optional)
public class CacheInterceptor implements Interceptor {
Context mContext;
public CacheInterceptor(Context context) {
this.mContext = context;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.method().equals("GET")) {
if (DeviceUtils.isConnected(mContext)) {
request = request.newBuilder()
.header(Constant.CACHE_CONTROL, "only-if-cached")
.build();
} else {
request = request.newBuilder()
.header(Constant.CACHE_CONTROL, "public, max-stale=2419200")
.build();
}
}
Response originalResponse = chain.proceed(request);
return originalResponse.newBuilder()
.header(Constant.CACHE_CONTROL, "max-age=600")
.build();
}
}
implement it
HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
logger.setLevel(HttpLoggingInterceptor.Level.BODY);
long SIZE_OF_CACHE = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(new File(mContext.getCacheDir(), "http"), SIZE_OF_CACHE);
new OkHttpClient.Builder()
.addInterceptor(logger)
.addInterceptor(new HeaderInterceptor(u))
.cache(cache)
.addNetworkInterceptor(new CacheInterceptor(mContext))
.connectTimeout(Constant.CONNECTTIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constant.READTIMEOUT, TimeUnit.SECONDS)
.writeTimeout(Constant.WRITETIMEOUT, TimeUnit.SECONDS)
.build();
Of course using auth interceptor is correct way (as explained in other answers). Although, if you need basic authentication only for single call, then auth header can be added directly in Retrofit request:
import okhttp3.Credentials
// Create credentials
val login = "some login"
val password = "some password"
// Below code will create correct Base64 encoded Basic Auth credentials
val credentials = Credentials.basic(login, password)
// Then in your Retrofit API interface
interface MyApi {
#POST("get_user")
fun getUser(#Header("Authorization") credentials: String): ResponseBody
}

Categories

Resources