安卓WSS客户端

  • 在app模块build.gradle中添加依赖
compile 'org.java-websocket:Java-WebSocket:1.3.0'
  • 实现WebSocketClien接口
public class WSS extends WebSocketClient {

    public static WSS newInstance(){
        WSS wss = null;
        try{
            wss = new WSS(new URI(Config.CHAT_SOCKET_ADDR));
        }catch (Exception e){
        }
        return wss;
    }

    public WSS(URI uri){
        super(uri);
        TrustManager[] trustAllCerts = new TrustManager[] { new TrustManager()};
        try{
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
        }catch (Exception ignored){}
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
    }

    @Override
    public void onMessage(String message) {
    }

    @Override
    public void onError(Exception ex) {
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
    }
}
  • 实现X509TrustManager
public class TrustManager implements X509TrustManager {

    private Certificate ca = null;

    public TrustManager(){
        try{
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(MyApplication.getApplication().getAssets().open("ca.crt"));
            try {
                ca = cf.generateCertificate(caInput);
            }finally {
                caInput.close();
            }
        } catch (CertificateException e1){
            e1.printStackTrace();
        } catch (IOException e2){
            e2.printStackTrace();
        }
    }

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[] {};
    }

    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
        for (X509Certificate cert : chain) {
            cert.checkValidity();
            try {
                cert.verify(((X509Certificate) ca).getPublicKey());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (SignatureException e) {
                e.printStackTrace();
            }
        }
    }
}

标签: android, wss

添加新评论