Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 784
4ndro1d Avatar asked Apr 12 '17 09:04

4ndro1d


People also ask

What is the difference between Retrofit and OkHttp?

OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.

How do you pass basic authentication in header Retrofit?

Approach. You will have to create a Request interceptor ( BasicAuthInterceptor ) which extends Interceptor class of OkHttp library. Then, override intercept function and add your credentials into the request. Generate basic credentials with Credentials class of package OkHttp by using its basic function.

What is Retrofit interceptor?

Retrofit is a popular, simple and flexible library to handle network requests in android development.


1 Answers

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(); 
like image 194
Rajasekhar Avatar answered Sep 19 '22 17:09

Rajasekhar