2014-11-22 48 views

回答

4

我用這個解決方案,也許它可以幫助你:

首先,你需要一個擴展類的SSLSocketFactory附上HandshakeCompletedListenerSSLSocketFactory創建的套接字: (由How to override the cipherlist sent to the server by Android when using HttpsURLConnection?啓發)

public class SecureSSLSocketFactory extends SSLSocketFactory { 
private final SSLSocketFactory delegate; 
private HandshakeCompletedListener handshakeListener; 

public SecureSSLSocketFactory(
     SSLSocketFactory delegate, HandshakeCompletedListener handshakeListener) { 
    this.delegate = delegate; 
    this.handshakeListener = handshakeListener; 
} 

@Override 
public Socket createSocket(Socket s, String host, int port, boolean autoClose) 
    throws IOException { 
    SSLSocket socket = (SSLSocket) this.delegate.createSocket(s, host, port, autoClose); 

    if (null != this.handshakeListener) { 
     socket.addHandshakeCompletedListener(this.handshakeListener); 
    } 

    return socket; 
} 
// and so on for all the other createSocket methods of SSLSocketFactory. 

@Override 
public String[] getDefaultCipherSuites() { 
    // TODO: or your own preferences 
    return this.delegate.getDefaultCipherSuites(); 
} 

@Override 
public String[] getSupportedCipherSuites() { 
    // TODO: or your own preferences 
    return this.delegate.getSupportedCipherSuites(); 
} 

然後,您需要實現HandshakeCompletedListener接口。您必須實現handshakeCompleted方法:

public class MyHandshakeCompletedListener implements HandshakeCompletedListener { 
@Override 
public void handshakeCompleted(HandshakeCompletedEvent event) { 
    SSLSession session = event.getSession(); 
    String protocol = session.getProtocol(); 
    String cipherSuite = session.getCipherSuite(); 
    String peerName = null; 

    try { 
     peerName = session.getPeerPrincipal().getName(); 
    } catch (SSLPeerUnverifiedException e) { 
    } 
} 

handshakeCompleted,你可以得到的協議版本(也許TLSv1.2工作),並順便也對密碼套件等信息,這也是通過HttpsConnection訪問。 您可以在連接之前通過conn.setSSLSocketFactory設置定製SSL插座工廠:

private void setupAndConnect() { 
URL url = new URL("https://host.dom/xyz"); 
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
SSLContext sslContext = SSLContext.getInstance("TLS"); 
sslContext.init(/*keyManagers*/null, /*trustManagers*/null, /*new SecureRandom()*/null); // simple here 

conn.setSSLSocketFactory(new SecureSSLSocketFactory(sslContext.getSocketFactory(), new MyHandshakeCompletedListener())); 

// conn.set... /* set other parameters */ 
conn.connect();