Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

trying to open a connection to a secure server (unknown certificate)

 
Bob Pettit
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My code looks like this:
-------------------------
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
System.out.println("before.");
url = new URL ("https://xml-test:8443/CCTranslator/servlet");
HttpURLConnection urlConn;
urlConn = (HttpURLConnection)url.openConnection();
System.out.println("after");
urlConn.setRequestMethod("POST");
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
String xmlString = "xmlRequest=" + URLEncoder.encode ( "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> bla bla bla"
System.out.println("2");
DataOutputStream printout = new DataOutputStream (urlConn.getOutputStream ());
System.out.println("3");
printout.writeBytes (xmlString);
System.out.println("4");
printout.flush ();
printout.close ();
input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
System.out.println("5");

When I type the URL (https://xml-test:8443/CCTranslator/servlet) in a browser it works fine. The program crashes and never prints the number (it prints number 2). I get an 'unknow certificate error'.
 
Bob Pettit
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I type the URL (https://xml-test:8443/CCTranslator/servlet) in a browser it works fine. The program crashes and never prints the number 3 (it prints number 2). I get an 'unknow certificate error'.
 
Lewin Chan
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this means the certificate sent by the server isn't trusted / known to your client.

When it works in the browser did you "accept the certificate for this session" or similar, if that's the case then it's definitely because servers certificate isn't trusted by your client.

If this is the case, you can either get the certificate from the server, and import it into the "cacerts" keystore in your jdk, or as a more amusing hack you could write a X509TrustManager implementation that always succeeds, from there, you can force your new AlwaysTrustManager to be used by the SSLContext, which can then provide the default SSLSocketFactory for HttpsURLConnection.

Something along these lines I would imagine.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic