我们正在使用OkHttp3 Client将请求发送到Jetty Http / 2服务器。我们希望通过客户端的特定网络接口路由请求。
我们尝试如下重写2个参数createSocket(InetAddress host,int port)方法
client = new OkHttpClient.Builder()
.socketFactory(new SocketFactory() {
final SocketFactory defaultSocketFactory = SocketFactory.getDefault();
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
LOG.info("4 argument create socket invoked {} {} {} {}", address, port, localAddress, localPort);
return defaultSocketFactory.createSocket(address, port, localAddress, localPort);
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
LOG.info("Another 4 argument create socket invoked {} {} {} {}", host, port, localHost, localPort);
return defaultSocketFactory.createSocket(host, port, localHost, localPort);
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
LOG.info("Expected Create socket invoked {} {} ", host, port);
return defaultSocketFactory.createSocket(InetAddress.getByName(dnsIPAddress), port);
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
LOG.info("Other 2 Argument Create socket invoked {} {} ", host, port);
return defaultSocketFactory.createSocket(host, port);
}
})
.connectTimeout(6000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.build();
为简洁起见,省略了构建SSL上下文的操作。
以上覆盖方法是否正确?我们没有取得预期的结果吗?
我们的需要是,请求应该从客户端通过指定的IP和端口进行路由。