我有一个JEditorPane
通过 SSL/TLS 加载网站。我的目标是(通过反射)获取 SSL 连接的特定信息,例如 SSL 握手的完成消息。我唯一得到的JEditorPane
是URL
,因此是HttpsURLConnection
.
但是我如何获得SSLSocket
的HttpsURLConnection
?有任何想法吗?
我有一个JEditorPane
通过 SSL/TLS 加载网站。我的目标是(通过反射)获取 SSL 连接的特定信息,例如 SSL 握手的完成消息。我唯一得到的JEditorPane
是URL
,因此是HttpsURLConnection
.
但是我如何获得SSLSocket
的HttpsURLConnection
?有任何想法吗?
没有直接的方法可以得到它。但是您可以控制 HttpsURLConnection 使用的 SSL 套接字。您可以在 httppsURLConnection.setSSLSocketFactory() 中设置套接字工厂。
您可以创建一个自定义套接字工厂,该工厂创建您自己的装饰 sslsocket 并将其返回。这将是您的 HttpsURLConnection 使用的套接字。
请注意,您需要在建立连接之前执行此操作。
SSLSocketFactory sslSktFactory = SSLContext.getInstance("TLS").getSocketFactory();
httpsUrlConnection.setSSLSocketFactory(new CustomSSLSocketFactory(sslSktFactory ));
下面是一个示例自定义 SSL 套接字工厂
class CustomSSLSocketFactory extends SSLSocketFactory {
SSLSocketFactory factory = null;
CustomSSLSocketFactory(SSLSocketFactory factory) {
this.factory = factory;
}
@Override
public Socket createSocket(Socket s, String host, int port,
boolean autoClose) throws IOException {
Socket skt = factory.createSocket(s, host, port, autoClose);
return customizeSSLSocket(skt);
}
@Override
public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
@Override
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
Socket skt = factory.createSocket(host, port);
return customizeSSLSocket(skt);
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
Socket skt = factory.createSocket(host, port);
return customizeSSLSocket(skt);
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost,
int localPort) throws IOException, UnknownHostException {
Socket skt = factory.createSocket(host, port, localHost, localPort);
return customizeSSLSocket(skt);
}
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException {
Socket skt = factory.createSocket(address, port, localAddress, localPort);
return customizeSSLSocket(skt);
}
private Socket customizeSSLSocket(Socket skt) throws SocketException {
((SSLSocket)skt).addHandshakeCompletedListener(
new HandshakeCompletedListener() {
public void handshakeCompleted(
HandshakeCompletedEvent event) {
System.out.println("Handshake finished!");
System.out.println(
"\t CipherSuite:" + event.getCipherSuite());
System.out.println(
"\t SessionId " + event.getSession());
System.out.println(
"\t PeerHost " + event.getSession().getPeerHost());
System.out.println(
"\t PeerHost " + event.getSession().getProtocol());
}
}
);
return skt;
}