I am reading from SSL Socket but host doesn't match the certificate (eg. host = "localhost"
). I would expect the exception but the following code happily talks to remote server without any problems.
try (
final Socket socket = SSLSocketFactory.getDefault().createSocket(host, port);
final OutputStream os = socket.getOutputStream();
final InputStream is = socket.getInputStream()) {
os.write(("HEAD / HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n").getBytes());
os.flush();
final byte[] bytes = new byte[1024];
int n;
while ((n = is.read(bytes)) != -1) {
System.out.print(new String(bytes, 0, n));
}
System.out.println();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Therefore I've tried another approach:
try {
final HttpURLConnection conn = (HttpURLConnection) new URL("https://" + host + ":" + port + "/").openConnection();
try (InputStream is = conn.getInputStream()) {
IOUtils.copy(is, System.out);
} catch (final IOException e1) {
try (InputStream es = conn.getErrorStream()) {
if (es != null) {
IOUtils.copy(es, System.out);
}
}
}
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately I still get no SSL exception, just WARN in the logs:
2013-07-31 16:02:27,182 WARN nio - javax.net.ssl.SSLException: Received fatal alert: certificate_unknown
How to get the SSL exception if certificate doesn't match?