If you are doing this with the latest version of Retrofit / OkHttp, the current set of solutions aren't sufficient. Retrofit no longer offers a RequestInterceptor, so you need to use OkHttp's interceptors to accomplish a similar task:
Create your interceptor:
public class HttpAuthInterceptor implements Interceptor {
private String httpUsername;
private String httpPassword;
public HttpAuthInterceptor(String httpUsername, String httpPassword) {
this.httpUsername = httpUsername;
this.httpPassword = httpPassword;
}
@Override public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", getAuthorizationValue())
.build();
return chain.proceed(newRequest);
}
private String getAuthorizationValue() {
final String userAndPassword = "httpUsername" + ":" + httpPassword;
return "Basic " + Base64.encodeToString(userAndPassword.getBytes(), Base64.NO_WRAP);
}
}
You'd need to add the interceptor to your OkHttp Client:
// Create your client
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpAuthInterceptor("httpUsername", "httpPassword"))
.build();
// Build Retrofit with your client
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.build();
// Create and use your service that now authenticates each request.
YourRetrofitService service = retrofit.create(YourRetrofitService.class);
I didn't test the above code, so some slight modifications may need to be made. I program in Kotlin for Android now-a-days.