Java访问https网站出现hostname wrong

来源:互联网 发布:h3c端口聚合配置验证 编辑:程序博客网 时间:2024/06/01 07:23
java.io.IOException: HTTPS hostname wrong: should be <localhost> 异常处理

java.io.IOException: HTTPS hostname wrong: should be <localhost>: 

    原因:当访问HTTPS的网址。您可能已经安装了服务器证书到您的JRE的keystore 。但这个错误是指服务器的名称与证书实际域名不相等。这通常发生在你使用的是非标准网上签发的证书。 

   解决方法:让JRE相信所有的证书和对系统的域名和证书域名。以下是一小段代码,可以用来实现这一目标。 

public class Servlet_test {

    public static void main(String[] args)throws Exception {
        URL url=new URL("https://localhost:8443/sso/servlet/SyncServlet?method=deleteOrg&appid=ec28d8fd22cf4bdf0122cf53e8a10002&orgcoding=001311&memo=");
        HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
        conn.setHostnameVerifier(new Servlet_test().new TrustAnyHostnameVerifier());
        conn.connect();
        InputStream ip= conn.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(ip));
        String line;
        StringBuffer strb = new StringBuffer();
        while ((line = br.readLine()) != null) {
            strb.append(line);
        }
        String ss = strb.toString();
        System.out.println(ss);
    }

    public class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            // 直接返回true
            return true;
        }
    }

    
}

如果你为服务器证书经常改变,而自己的客户端方也跟随改变而头痛的话,以上方法也适合。

0 0
原创粉丝点击