4

If I use the following code because I want to, for example, to change the way certificates are validated.

trm = some trust manager

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { trm }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

Then this sets the SSLContext for all https connections that will be made in the future regardless of what thread. What is the cleanest way to control the scope so that I set it only for those calls I want?

che javara
  • 748
  • 1
  • 8
  • 18

1 Answers1

12

You can set the socket factory on the actual connection object that you want to have use this trust store:

HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sc.getSocketFactory());

Do that instead of invoking setDefaultSSLSocketFactory.

laz
  • 28,320
  • 5
  • 53
  • 50
  • thanks that sounds like it should work, but do you know of any other way that would not require you to obtain an instance of HttpsURLConnection ? – che javara May 17 '11 at 15:31
  • Are you not using HTTP? What type of connection is using the SSL sockets? – laz May 17 '11 at 16:08
  • @che javara You get an HttpsURLConnection every time you use an HTTPS URL in Java. It's not an extra step. Your question doesn't make sense. – user207421 May 18 '11 at 01:12
  • 1
    Lets say I'm using a higher level messaging framework that uses http under the cover so I don't have direct access to modify the HttpsURLConnection instance – che javara May 18 '11 at 14:09
  • 1
    You would need to rely on that framework's mechanism for providing an alternative socket factory then. If those details aren't exposed by the framework you will need to rely on the global settings. In that case, you could provide a subclass of `TrustManager` that only performs the differing behavior on selected hosts and falls back to the original `TrustManager` for all others. – laz May 18 '11 at 15:42
  • excellent answer Iaz, I was leaning toward that but for some reason thought there was a 'cleaner' global way. – che javara May 18 '11 at 16:22