Tomcat8配置SSL/TSL,Android通過HTTPS進行訪問

最近需要在Android上通過HTTPS協議訪問Tomcat服務器,這裏做一下記錄,備忘用。

一、Tomcat上的配置

1.生成keystore文件

在JDK_HOME/bin目錄下有一個keytool工具,可用來生成一個存放服務器私鑰和自簽名證書的文件。使用如下命令來生成這個文件,
keytool -v -genkey -alias cyber_space -keyalg RSA -keystore /home/cyber_space/KEYS/cyber_space.keystore -validity 36500
其中,validity是有效時間,這裏定成了100年。其他的參數意思都可以從英文單詞中直接得出。
接下來按下圖步驟進行操作。


2.配置TOMCAT_HOME/conf目錄下的server.xml文件

在配置文件中添加如下的內容,或將註釋部分去掉修改爲如下。
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" keystoreFile="/home/cyber_space/KEYS/cyber_space.keystore" keystorePass="密碼"/>

3.重新啓動Tomcat,使用瀏覽器訪問https://IP:8843

看是否可以訪問Tomcat,這裏可能會遇到證書不受信任問題,只要讓瀏覽器信任證書,就可以訪問了。

4.修改工程目錄下的web.xml文件

如果要讓HTTP訪問自動轉換爲HTTPS訪問,則在相應的工程目錄下修改web.xml文件,增加如下配置。
<security-constraint>
		<web-resource-collection>
			<web-resource-name>SSL</web-resource-name>
			<url-pattern>/TestServlet</url-pattern>
		</web-resource-collection>
		<user-data-constraint>
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		</user-data-constraint>
</security-constraint>
其中UrlPattern即是你想要自動轉換爲HTTPS請求的地址。

二、Android端代碼

下面代碼的寫法表示Android應用程序信任所有證書。
package com.example.justyoung.logintest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by justyoung on 15/6/25.
 */
public class HttpsConnection {

    public void httpsRequestThread(String url) {
        new HttpsRequestThread(url).start();
    }

    /**
     * 發起HTTPS請求,並返回結果
     *
     * @param url https連接
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     * @return  返回服務器輸出結果
     */
    private static String httpsRequest(String url) throws NoSuchAlgorithmException, KeyManagementException, IOException {
        StringBuilder stringBuilder = new StringBuilder();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setConnectTimeout(10000);
        connection.connect();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        String result = stringBuilder.toString();
        System.out.println(result);
        return result;
    }

    private static class MyHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static class MyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    private class HttpsRequestThread extends Thread {
        private String url;

        public HttpsRequestThread(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            try {
                httpsRequest(this.url);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}










發佈了53 篇原創文章 · 獲贊 5 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章