Skip to content

Instantly share code, notes, and snippets.

@ffgiraldez
Created November 16, 2016 08:45
Show Gist options
  • Save ffgiraldez/498da62a225893426de95ce6a3ddf835 to your computer and use it in GitHub Desktop.
Save ffgiraldez/498da62a225893426de95ce6a3ddf835 to your computer and use it in GitHub Desktop.
Change host at runtime with Retrofit 2
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