Retrofit and OkHttp basic authentication

后端 未结 3 1379
[愿得一人]
[愿得一人] 2020-12-12 17:24

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 createMM         


        
3条回答
  •  温柔的废话
    2020-12-12 17:54

    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();
    

提交回复
热议问题