Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This OkHttp application interceptor will replace the destination hostname in the request URL.
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/** An interceptor that allows runtime changes to the URL hostname. */
public final class HostSelectionInterceptor implements Interceptor {
private volatile String host;
public void setHost(String host) { = host;
@Override public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String host =;
if (host != null) {
HttpUrl newUrl = request.url().newBuilder()
request = request.newBuilder()
return chain.proceed(request);
public static void main(String[] args) throws Exception {
HostSelectionInterceptor interceptor = new HostSelectionInterceptor();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
Request request = new Request.Builder()
okhttp3.Call call1 = okHttpClient.newCall(request);
okhttp3.Response response1 = call1.execute();
System.out.println("RESPONSE FROM: " + response1.request().url());
okhttp3.Call call2 = okHttpClient.newCall(request);
okhttp3.Response response2 = call2.execute();
System.out.println("RESPONSE FROM: " + response2.request().url());
Copy link

@iBotasky Because the network request is asynchronous, try

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment