我正在从 SSL Socket 读取,但主机与证书不匹配(例如。host = "localhost"
)。我预计会出现异常,但以下代码可以愉快地与远程服务器通信,没有任何问题。
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();
}
因此我尝试了另一种方法:
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();
}
不幸的是,我仍然没有收到 SSL 异常,只是在日志中发出警告:
2013-07-31 16:02:27,182 WARN nio - javax.net.ssl.SSLException: Received fatal alert: certificate_unknown
如果证书不匹配,如何获取 SSL 异常?