Created
November 16, 2016 08:45
-
-
Save ffgiraldez/498da62a225893426de95ce6a3ddf835 to your computer and use it in GitHub Desktop.
Change host at runtime with Retrofit 2
This file contains 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
public abstract class EndpointInterceptor implements Interceptor { | |
@Override | |
public Response intercept(Chain chain) throws IOException { | |
Request originalRequest = chain.request(); | |
HttpUrl newUrl = replaceHost(originalRequest); | |
Request completeRequest = originalRequest.newBuilder() | |
.url(newUrl) | |
.build(); | |
return chain.proceed(completeRequest); | |
} | |
@NonNull | |
private HttpUrl replaceHost(Request originalRequest) { | |
HttpUrl originalUrl = originalRequest.httpUrl(); | |
return originalUrl.newBuilder() | |
.host(getHost()) | |
.build(); | |
} | |
@NonNull | |
private String getHost() { | |
String url = getUrl(); | |
if (url.endsWith("/")) { | |
url = new StringBuilder(url) | |
.deleteCharAt(url.length() - 1) | |
.toString(); | |
} | |
return HttpUrl.parse(url) | |
.host(); | |
} | |
protected abstract String getUrl(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment