OkHttp newBuilder () set socketFactory не указывать сетевой интерфейс без установленного proxyAuthenticator? - PullRequest
0 голосов
/ 27 мая 2020

Я хочу указать сетевой интерфейс для запроса с OkHttpClient (создать с newBuilder()). Я использую класс DelegatingSocketFactory , а затем пытаюсь выполнить привязку, чтобы указать адрес c с использованием socketFactory . Первый без набора proxyAuthenticator, я вижу, что сетевой интерфейс не меняется, затем попробуйте добавить proxyAuthenticator, все работают хорошо. Как внести изменения в интерфейс локальной сети для запроса, не задавая proxyAuthenticator.

У меня есть 2 адреса 192.168.0.9 и 192.168.0.16 соответствующие Ethe rnet и WiFi .

Попробуйте запустить Windows 10, Java 8 и реализацию («com.squareup.okhttp3:okhttp:4.7.2»)

Основной код:

public static void main(String args[]) throws SocketException {

    LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
    OkHttpClient appOkHttpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(loggingInterceptor)
            .build();

    OkHttpClient okHttpClient1 = appOkHttpClient.newBuilder()
            .socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
                @Override
                protected Socket configureSocket(Socket socket) throws IOException {
                    socket.bind(new InetSocketAddress("192.168.0.16", 0));
                    return socket;
                }
            })
            .proxyAuthenticator((route, response) -> response.request().newBuilder()
                    .build())
            .build();


    OkHttpClient okHttpClient2 = appOkHttpClient.newBuilder()
            .socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
                @Override
                protected Socket configureSocket(Socket socket) throws IOException {
                    socket.bind(new InetSocketAddress("192.168.0.9", 0));
                    return socket;
                }
            })
            .proxyAuthenticator((route, response) -> response.request().newBuilder()
                    .build())
            .build();
    OkHttpClient okHttpClient3 = appOkHttpClient.newBuilder()
            .socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
                @Override
                protected Socket configureSocket(Socket socket) throws IOException {
                    socket.bind(new InetSocketAddress("192.168.0.16", 0));
                    return socket;
                }
            }).build();


    OkHttpClient okHttpClient4 = appOkHttpClient.newBuilder()
            .socketFactory(new DelegatingSocketFactory(SocketFactory.getDefault()) {
                @Override
                protected Socket configureSocket(Socket socket) throws IOException {
                    socket.bind(new InetSocketAddress("192.168.0.9", 0));
                    return socket;
                }
            }).build();


    Request request = new Request.Builder()
            .url("http://api.ipify.org/?format=json")
            .build();

    try (Response response = appOkHttpClient.newCall(request).execute()) {
        String result = response.body().string();
        System.out.println("App result :" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }


    try (Response response = okHttpClient1.newCall(request).execute()) {
        String result = response.body().string();
        System.out.println("With set result 1:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
    try (Response response = okHttpClient2.newCall(request).execute()) {
        String result = response.body().string();
        System.out.println("With set result 2:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try (Response response = okHttpClient3.newCall(request).execute()) {
        String result = response.body().string();
        System.out.println("Not set result 3:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
    try (Response response = okHttpClient4.newCall(request).execute()) {
        String result = response.body().string();
        System.out.println("Not set result 4:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

LoggingInterceptor :

public class LoggingInterceptor implements Interceptor {

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();

        Connection connection = chain.connection();
        Socket socket = connection.socket();

        System.out.println(String.format("Sending request %s via LocalAddress: %s",
                request.url(), socket.getLocalAddress().getHostAddress()));
        return chain.proceed(request);

    }
}

Вывод:

Sending request http://api.ipify.org/?format=json via LocalAddress: 192.168.0.9
App result :{"ip":"42.116.156.194"}
Sending request http://api.ipify.org/?format=json via LocalAddress: 192.168.0.16
With set result 1:{"ip":"42.116.156.194"}
Sending request http://api.ipify.org/?format=json via LocalAddress: 192.168.0.9
With set result 2:{"ip":"42.116.156.194"}
Sending request http://api.ipify.org/?format=json via LocalAddress: 192.168.0.9
Not set result 3:{"ip":"42.116.156.194"}
Sending request http://api.ipify.org/?format=json via LocalAddress: 192.168.0.9
Not set result 4:{"ip":"42.116.156.194"}
...