无法建立SSL连接

时间:2016-11-15 07:05:30

标签: android ssl

我使用下面的代码进行SSL连接。

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = mcontext.getAssets().open("idashboard.cer");
        Certificate ca = null;
        try {
            ca = cf.generateCertificate(caInput);
            System.out.println("ca=" + ((X509Certificate)   ca).getSubjectDN());
        }catch (CertificateException e4) {
            e4.printStackTrace();
        }finally {
            try{
                caInput.close();}catch (Exception e5){
                e5.printStackTrace();
            }
        }

        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf =   TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        // Tell the URLConnection to use a SocketFactory from our SSLContext
        URL murl = new URL("My URL Here");
        HttpsURLConnection urlConnection =
                (HttpsURLConnection)murl.openConnection();
        urlConnection.setHostnameVerifier(new NullHostNameVerifier());
        urlConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        urlConnection.setSSLSocketFactory(context.getSocketFactory());
        InputStream in = urlConnection.getInputStream(); //GETTING ERROR AT THIS LINE


        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder result = new StringBuilder();
        String line;
        while((line = reader.readLine()) != null) {
            result.append(line);
        }

在输入流行(InputStream in = urlConnection.getInputStream();)中,它将验证NullHostNameVerifier()的方法,当它返回true时,不知道它发生了什么,它来到设备主屏幕,我不知道它崩溃或什么,因为我没有得到崩溃弹出窗口。

以下是hostnameVerifier的代码

public class NullHostNameVerifier implements HostnameVerifier {

    @Override
    public boolean verify(String hostname, SSLSession session) {

        return true;
    }

}

我在网络方面很差,无法理解正在发生的事情。此请求我必须作为获取和发布两个

我错过了任何一行代码吗?另外,我如何制作get和post请求以及如何解析输入流的响应

任何帮助?

先谢谢

0 个答案:

没有答案