美文网首页
Android端使用AsyncHttpClient与服务端进行h

Android端使用AsyncHttpClient与服务端进行h

作者: Tenny1225 | 来源:发表于2016-04-11 18:28 被阅读4053次

    首先需要获得 服务器端需要验证的客户端证书,即.p12文件

    获得客户端信任的服务器端证书,即.bks或者.truststore文件

    private static final String KEY_STORE_TYPE_BKS = "bks";
    private static final String KEY_STORE_TYPE_P12 = "PKCS12";
    private static final String KEY_STORE_PASSWORD = "123456";
    private static final String KEY_STORE_TRUST_PASSWORD = "123456";
    private SSLSocketFactory getSocketFactory() {
            SSLSocketFactory socketFactory=null;
            try {
                // 服务器端需要验证的客户端证书
                keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
    
                // 客户端信任的服务器端证书
                trustStore = KeyStore.getInstance(KEY_STORE_TYPE_BKS);
    
              //.p12文件  
    InputStream ksIn = this.getResources().openRawResource(R.raw.client);
    //.bks文件
                InputStream tsIn = this.getResources().openRawResource(R.raw.server_bks);
                try {
                    keyStore.load(ksIn, KEY_STORE_PASSWORD.toCharArray());
                    trustStore.load(tsIn, KEY_STORE_TRUST_PASSWORD.toCharArray());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        ksIn.close();
                    } catch (Exception ignore) {
                    }
                    try {
                        tsIn.close();
                    } catch (Exception ignore) {
                    }
                }
    
                socketFactory = new SSLSocketFactory(keyStore, KEY_STORE_PASSWORD, trustStore);
                socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (UnrecoverableKeyException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return  socketFactory;
        }
    

    然后在代码中调用一下就行了

    AsyncHttpClient mAsyncHttpClient = new AsyncHttpClient();
    mAsyncHttpClient.setSSLSocketFactory(getSocketFactory());
    

    相关文章

      网友评论

          本文标题:Android端使用AsyncHttpClient与服务端进行h

          本文链接:https://www.haomeiwen.com/subject/weuilttx.html