在JAVA中发出HTTPS请求并打开SSL套接字

时间:2013-06-26 09:26:01

标签: ssl https javafx

我正在尝试构建一个登录页面。为此,我想打开SSL套接字并发出HTTPS请求,但我m getting Unknown Host Exception in line-- SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443); Could someone please tell me what I做错了吗?此外,我已经关闭了主机验证,因为我的程序中不需要它。

`public void clickLogin() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {


            URL url = new URL ("https://31.21.18.222/room_info/x.txt");
            HttpsURLConnection connection = null;
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);        //Make an empty store
            InputStream fis = new FileInputStream("C:/Documents and Settings/user/Desktop/PK/localhost.crt"); 
            BufferedInputStream bis = new BufferedInputStream(fis);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            while (bis.available() > 0) {
                java.security.cert.Certificate cert = cf.generateCertificate(bis);
                keyStore.setCertificateEntry("localhost", cert);
            }

            // write code for turning off client verification
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(null, tmf.getTrustManagers() , null);
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            SSLSocketFactory sslsf = context.getSocketFactory();
            SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443);
            skt.setUseClientMode(true);
            SSLSession s = skt.getSession(); // handshake implicitly done
            skt.setKeepAlive(true);


            connection = (HttpsURLConnection) url.openConnection();

        // Host name verification off
            connection.setHostnameVerifier(new HostnameVerifier()  
            {        
                public boolean verify(String hostname, SSLSession session)  
                {  
                    return true;  
                }  
            });  `

1 个答案:

答案 0 :(得分:2)

如果要打开createSocket的套接字,则需要使用主机名(或IP地址),而不是完整的URL:

example : sslsf.createSocket("31.21.18.222" , 443);

另外:

  • 请勿使用Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider())(默认设置为此处)。
  • 最好使用TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())代替X.509,尤其是因为TMF的默认算法是PKIX,而不是X.509
  • createSocket将根据信任锚验证证书,但不会检查主机名(这也是防止MITM攻击所必需的)。为此,使用主机名而不是IP地址通常也更好。