Add support for proxy auth

Signed-off-by: Mario Danic <mario@lovelyhq.com>
This commit is contained in:
Mario Danic 2017-10-25 22:37:57 +02:00
parent 918e0085a4
commit 7442340105
2 changed files with 34 additions and 1 deletions

View File

@ -41,11 +41,14 @@ import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Authenticator;
import okhttp3.Cache;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
@ -86,7 +89,7 @@ public class RestModule {
@Provides
@Singleton
OkHttpClient provideHttpClient(@Nullable Proxy proxy) {
OkHttpClient provideHttpClient(@Nullable Proxy proxy, AppPreferences appPreferences) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
int cacheSize = 128 * 1024 * 1024; // 128 MB
@ -102,6 +105,13 @@ public class RestModule {
if (proxy != null) {
httpClient.proxy(proxy);
if (!TextUtils.isEmpty(appPreferences.getProxyServer().getUsername()) &&
!TextUtils.isEmpty(appPreferences.getProxyServer().getPassword())) {
httpClient.proxyAuthenticator(new ProxyAuthenticator(Credentials.basic(
appPreferences.getProxyServer().getUsername(),
appPreferences.getProxyServer().getPassword())));
}
}
httpClient.addInterceptor(new HeadersInterceptor());
@ -109,6 +119,23 @@ public class RestModule {
return httpClient.build();
}
private class ProxyAuthenticator implements Authenticator {
private String credentials;
private ProxyAuthenticator(String credentials) {
this.credentials = credentials;
}
@Nullable
@Override
public Request authenticate(@NonNull Route route, @NonNull Response response) throws IOException {
return response.request().newBuilder()
.header("Proxy-Authorization", credentials)
.build();
}
}
private class HeadersInterceptor implements Interceptor {
@Override

View File

@ -40,4 +40,10 @@ public class ProxyPrefs {
@JsonField(name = "proxy_type")
String proxyType;
@JsonField(name = "username")
String username;
@JsonField(name = "password")
String password;
}