Last active
May 17, 2024 19:11
-
-
Save swankjesse/8571a8207a5815cca1fb to your computer and use it in GitHub Desktop.
This OkHttp application interceptor will replace the destination hostname in the request URL.
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
import java.io.IOException; | |
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) { | |
this.host = host; | |
} | |
@Override public okhttp3.Response intercept(Chain chain) throws IOException { | |
Request request = chain.request(); | |
String host = this.host; | |
if (host != null) { | |
HttpUrl newUrl = request.url().newBuilder() | |
.host(host) | |
.build(); | |
request = request.newBuilder() | |
.url(newUrl) | |
.build(); | |
} | |
return chain.proceed(request); | |
} | |
public static void main(String[] args) throws Exception { | |
HostSelectionInterceptor interceptor = new HostSelectionInterceptor(); | |
OkHttpClient okHttpClient = new OkHttpClient.Builder() | |
.addInterceptor(interceptor) | |
.build(); | |
Request request = new Request.Builder() | |
.url("http://www.coca-cola.com/robots.txt") | |
.build(); | |
okhttp3.Call call1 = okHttpClient.newCall(request); | |
okhttp3.Response response1 = call1.execute(); | |
System.out.println("RESPONSE FROM: " + response1.request().url()); | |
System.out.println(response1.body().string()); | |
interceptor.setHost("www.pepsi.com"); | |
okhttp3.Call call2 = okHttpClient.newCall(request); | |
okhttp3.Response response2 = call2.execute(); | |
System.out.println("RESPONSE FROM: " + response2.request().url()); | |
System.out.println(response2.body().string()); | |
} | |
} |
@iBotasky Because the network request is asynchronous, try https://github.com/JessYanCoding/RetrofitUrlManager
I have a good implementation plan, which will be easier to use and solve the problem more thoroughly. Welcome everyone to try https://github.com/uni-cstar/oknet
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@JessYanCoding
I request two api with different baseUrl at the same time, one of the request's baseUrl is wrong.
The two baseurl are:
http://gank.io/
andhttps://api.douban.com/
And occur this:
D/OkHttp: <-- 404 Not Found http://gank.io/v2/movie/in_theaters (308ms)
This is wrong because the base url is
https://api.douban.com/
but nothttp://gank.io/
I think it course by concurrency with the
Volatile
, how solve it?