OkHttp通过wifi和SocketFactory路由流量

问题描述 投票:0回答:1

我需要路由特定请求抛出wifi,甚至wifi“连接,没有互联网”和“移动数据”打开。

下面的示例适用于HttpURLConnection,但不适用于OkHttp3(3.8.1),它是app的主要网络库:

下面的代码按预期使用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不能像我理解的那样工作,或者我简单地遗漏了一些东西。

android okhttp okhttp3 android-networking okhttpclient
1个回答
1
投票

最后,我找到了。

https://github.com/square/okhttp/commit/2a5fb08b39195d4238c7117e851e9221f94de62a#diff-ec23bee7240c28053b0ca4fbc6029529

因此,如果您想获得旧的行为(如在3.4.2版本中),您可以使用java.net.ProxySelector.getDefault()并将其包装为也尝试NO_PROXY。

在我的情况下,如上所述,我需要在添加socketFactory之前手动禁用代理:

builder.proxy(Proxy.NO_PROXY);
builder.socketFactory(network.getSocketFactory());
© www.soinside.com 2019 - 2024. All rights reserved.