2015年12月31日 星期四

Apache CloseableHttpClient 使用SSL (舊式)

sending post data to https without ssl cert verification with apache httpClient client
客戶端用https連接服務器


public String sendPost(final String request, final String postData) throws ClientProtocolException, IOException, NoSuchAlgorithmException, KeyManagementException  {
    String result = null;
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                        System.out.println("getAcceptedIssuers =============");
                        return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                                String authType) {
                        System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                                String authType) {
                        System.out.println("checkServerTrusted =============");
                }
    } }, new SecureRandom());

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(new SSLSocketFactory(sslContext)).build();
    HttpPost httpPost = new HttpPost(request);
    ByteArrayEntity postDataEntity = new ByteArrayEntity(postData.getBytes());
    httpPost.setEntity(postDataEntity);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return result;

}


xxxCer 指的是 憑證當初建立的名稱
javax.net.ssl.SSLException: hostname in certificate didn't match: <127.0.0.1> != <xxxCer>
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:238)
at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:159)



一個network和ip綁定的問題,但是這個綁定不是DNS來做,而是本機(windows系統)來做。查了一下,果然有,就在C:\WINDOWS\system32\drivers\etc下有一個host文件,打開它,可以看到這麼一行
127.0.0.1 localhost 

新增ip與host對應名稱,  如下

ex:
host:
127.0.0.1 testSSL

url:
https://testSSL:8443/ws/changeStatus

沒有留言:

張貼留言