OkHttp 路由流量抛出 wifi 和 SocketFactory
OkHttp route traffic throw wifi and SocketFactory
我需要路由特定请求抛出 wifi,即使 wifi "Connected, no internet" 和 "Mobile Data" 已打开。
以下示例适用于 HttpURLConnection
,但不适用于应用的主要网络库 OkHttp3 (3.8.1):
下面的代码在 OkHttp 版本中按预期工作:3.4.2
但自 OkHttp 版本以来已损坏:3.5.0
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final Network[] networks = connectivityManager.getAllNetworks();
for (final Network network : networks) {
final NetworkInfo netInfo = connectivityManager.getNetworkInfo(network);
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.getState() == NetworkInfo.State.CONNECTED) {
// just for example HttpURLConnection works as expected and route traffic throw wifi
connection = (HttpURLConnection) network.openConnection(url);
// not works since >=3.5.0, route traffic in same way
builder.socketFactory(network.getSocketFactory());
}
}
}
OkHttpClient client = builder.build();
final Response response = client.newCall(initialRequest).execute();
client.newCall 没有像我理解的那样工作,或者我只是遗漏了一些东西。
终于找到了
因此,如果您想恢复旧行为(如 3.4.2 版本),您可以使用 java.net.ProxySelector.getDefault() 并用同样尝试 NO_PROXY.[=12 的行为将其包装起来=]
在我的例子中,如上所述,我需要在添加 socketFactory 之前手动禁用代理:
builder.proxy(Proxy.NO_PROXY);
builder.socketFactory(network.getSocketFactory());
我需要路由特定请求抛出 wifi,即使 wifi "Connected, no internet" 和 "Mobile Data" 已打开。
以下示例适用于 HttpURLConnection
,但不适用于应用的主要网络库 OkHttp3 (3.8.1):
下面的代码在 OkHttp 版本中按预期工作:3.4.2
但自 OkHttp 版本以来已损坏:3.5.0
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final Network[] networks = connectivityManager.getAllNetworks();
for (final Network network : networks) {
final NetworkInfo netInfo = connectivityManager.getNetworkInfo(network);
if (netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.getState() == NetworkInfo.State.CONNECTED) {
// just for example HttpURLConnection works as expected and route traffic throw wifi
connection = (HttpURLConnection) network.openConnection(url);
// not works since >=3.5.0, route traffic in same way
builder.socketFactory(network.getSocketFactory());
}
}
}
OkHttpClient client = builder.build();
final Response response = client.newCall(initialRequest).execute();
client.newCall 没有像我理解的那样工作,或者我只是遗漏了一些东西。
终于找到了
因此,如果您想恢复旧行为(如 3.4.2 版本),您可以使用 java.net.ProxySelector.getDefault() 并用同样尝试 NO_PROXY.[=12 的行为将其包装起来=]
在我的例子中,如上所述,我需要在添加 socketFactory 之前手动禁用代理:
builder.proxy(Proxy.NO_PROXY);
builder.socketFactory(network.getSocketFactory());