Last active
February 12, 2023 07:13
-
-
Save iamnaran/daea198255e511fa7017b47b7b638f27 to your computer and use it in GitHub Desktop.
Host Selection Interceptor Retrofit Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Created by NaRan on 9/2/21, 3:44 PM | |
* Last modified 9/2/21, 3:44 PM | |
* Copyright (c) 2021 . | |
* All rights reserved. | |
* | |
*/ | |
import org.jetbrains.annotations.NotNull; | |
import java.io.IOException; | |
import java.net.URISyntaxException; | |
import java.util.Objects; | |
import javax.inject.Inject; | |
import javax.inject.Singleton; | |
import okhttp3.HttpUrl; | |
import okhttp3.Interceptor; | |
import okhttp3.Request; | |
/* | |
Solution from @swankjesse | |
Host Selection Retrofit | |
More at @link https://github.com/square/retrofit/issues/1404#issuecomment-207408548 | |
*/ | |
@Singleton | |
public class HostSelectionInterceptor implements Interceptor { | |
private volatile HttpUrl host = HttpUrl.parse(BuildConfig.DEVELOPMENT_BASE_URL); | |
PreferenceHelper preferenceHelper; | |
@Inject | |
public HostSelectionInterceptor(PreferenceHelper preferenceHelper){ | |
this.preferenceHelper = preferenceHelper; | |
setHostBaseUrl(); | |
} | |
public void setHostBaseUrl() { | |
if (preferenceHelper.isProdEnvironment()) { | |
this.host = HttpUrl.parse(BuildConfig.PRODUCTION_BASE_URL); | |
} else { | |
this.host = HttpUrl.parse(BuildConfig.DEVELOPMENT_BASE_URL); | |
} | |
} | |
@NotNull | |
@Override | |
public okhttp3.Response intercept(Chain chain) throws IOException { | |
Request request = chain.request(); | |
if (host != null) { | |
HttpUrl newUrl = null; | |
try { | |
newUrl = request.url().newBuilder() | |
.scheme(host.scheme()) | |
.host(host.url().toURI().getHost()) | |
.build(); | |
} catch (URISyntaxException e) { | |
e.printStackTrace(); | |
} | |
assert newUrl != null; | |
request = request.newBuilder() | |
.url(newUrl) | |
.build(); | |
} | |
return chain.proceed(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment