I'm trying to reach my server from WiFi or Mobile Data, depending on which interface is answering. The use case is the following : - WiFi is always on. - If the server is not responding through the WiFi (because there is no internet connection for example), then I redirect future requests to the cellular data. - When the connection is back through the WiFi, I redirect next requests to the WiFi.
To achieve this, I wanted to use the ConnectivityManager with TRANSPORT_CELLULAR or TRANSPORT_WIFI. Then it returns a Network object which I can use.
After that I planned to pass the socketFactory from the Network class to the OkHttpClient.
OkHttpClient client = new OkHttpClient.Builder()
.socketFactory(network.getSocketFactory())
.build();
Problem : the server uses a https connection. So I'm building the OkHttpClient using socketSSLFactory, which is build with SSLContext and its method getSocketFactory.
So the question is the following : how can I bind the OkHttpClient to a Network AND to a SSL Socket Factory ?
Ok so I finally find out how to perform that. It requires to use both socketFactory and SSLSocketFactory of OkHttp builder.
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
.sslSocketFactory(new MySSLSocketFactory(), new MyTrustManager())
.socketFactory(network.getSocketFactory())
.dns(new NetworkDns())
.hostnameVerifier(new MyHostnameVerifier());
Concretely, MySSLSocketFactory is not binded to my network object. I don't need to override the createSocket method in it. I just pass the socket factory of my network object to the OkHttp builder.
Don't forget to override the dns as well to perform the name resolution on the network you want. (cf Perform network-specific host name resolutions using Network.getAllByName)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With