Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Java HttpsURLConnection SSLSocketFactory timeout with trustAllCerts

User_JO36SOct 22 2021

Using Method-1 below to connect works, it trusts all certificates, even self signed certs, but the timeout does not work as well as Method-2.
But when I use Method-2, not all certs are trusted and it fails for self signed certs. I understand this is because in Method-2 I did not use my sslSocfactory which incorporates the trustAllCerts. I can't figure out how to incorporate my sslSocfactory into Method-2. I've tried a few ways but the compile fails.

 SSLSocket socket = null;
 SSLContext sc = null;
 sc = SSLContext.getInstance("TLS");
 sc.init(null, trustAllCerts, new java.security.SecureRandom());
 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 SSLSocketFactory sslSocfactory = HttpsURLConnection.getDefaultSSLSocketFactory();
  
 //--- Method-1 connection -----
  socket = (SSLSocket)sslSocfactory.createSocket(host, port);
  socket.setSoTimeout(timeout);      

 //--- Method-2 connection -----
  socket = (SSLSocket)SSLSocketFactory.getDefault().createSocket();
  socket.connect(new InetSocketAddress(host, port), timeout); //- This is the timeout that works for my situation
  socket.setSoTimeout(timeout);
Comments
Post Details
Added on Oct 22 2021
0 comments
821 views