间接Apache HttpClient和javax.net.ssl.SSLException:证书中的主机名不匹配

时间:2013-09-06 12:04:44

标签: java ssl https httpclient

我使用的是使用Apache HttpClient的库(Dasein)。

当我尝试使用自签名证书进行HTTPS连接(通过Dasein和HttpClient)到我的服务器时,我得到了 javax.net.ssl.SSLException: hostname in certificate didn't match

Caused by: javax.net.ssl.SSLException: hostname in certificate didn't match: <172.16.2.152> != at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:228) at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54) at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:149) at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:130) at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:572)

我已经将证书导入信任库并使用-Djavax.net.ssl.trustStore。 要修复这个不匹配的主机名,我的代码

    javax.net.ssl.HostnameVerifier fakeHostnameVerifier = new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
            return true;
        }
    };
    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(fakeHostnameVerifier);

    com.sun.net.ssl.HostnameVerifier fakeSunHostnameVerifier = new com.sun.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String string, String string1) {
            return true;
        }
    };
    com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(fakeSunHostnameVerifier);

当我尝试通过new URL("https://my.server.com/api/versions")直接从我的代码连接到该服务器时,由于hostNameVerifier,一切都很好。当调用HttpClient时,它似乎不会传播或被覆盖。

任何想法如何解决这个问题?例如。一些VM参数?

由于

1 个答案:

答案 0 :(得分:0)

我只是将证书中的主机名条目添加到我的/ etc / hosts中,并引用该FQDN。问题解决了。