Tomcat创建HTTPS访问,java访问https

一 https和ssL

HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版。即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL。 它是一个URI scheme(抽象标识符体系),句法类同http:体系。用于安全的HTTP数据传输。https:URL表明它使用了HTTP,但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层(在HTTP与TCP之间)。这个系统的最初研发由网景公司(Netscape)进行,并内置于其浏览器Netscape Navigator中,提供了身份验证与加密通讯方法。

Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are technologies which allow web browsers and web servers to communicate over a secured connection. This means that the data being sent is encrypted by one side, transmitted, then decrypted by the other side before processing. This is a two-way process, meaning that both the server AND the browser encrypt all traffic before sending out data.

TLS(全称:Transport Layer Security), 它的前身是SSL(全称:Secure Sockets Layer)。是为网络通信提供安全及数据完整性的一种安全协议。TLS与SSL在传输层对网络连接进行加密。

Another important aspect of the SSL/TLS protocol is Authentication. This means that during your initial attempt to communicate with a web server over a secure connection, that server will present your web browser with a set of credentials, in the form of a "Certificate", as proof the site is who and what it claims to be. In certain cases, the server may also request a Certificate from your web browser, asking for proof that you are who you claim to be. This is known as "Client Authentication," although in practice this is used more for business-to-business (B2B) transactions than with individual users. Most SSL-enabled web servers do not request Client Authentication.

二 Tomcat创建https访问

详细官方文档:http://tomcat.apache.org/tomcat-8.0-doc/ssl-howto.html

1. 生成keystore文件

注意生成的过程,后面会发现其实name是为了限定域名。

Windows:

"%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA
  -keystore \path\to\my\keystore

Unix:

$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA   -keystore /path/to/my/keystore

2. 修改tomcat/conf/server.xml

<!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<Connector
           protocol="org.apache.coyote.http11.Http11NioProtocol"
           port="8443" maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           keystoreFile="${user.home}/.keystore" keystorePass="changeit"
           clientAuth="false" sslProtocol="TLS"/>                              

注意keystore文件位置以及密码。

3.启动一个web项目

 1 Using CATALINA_BASE:   "C:\Users\miaorf\.IntelliJIdea2016.1\system\tomcat\Unnamed_spmvtest"
 2 Using CATALINA_HOME:   "D:\Java\apache-tomcat-8.0.33"
 3 Using CATALINA_TMPDIR: "D:\Java\apache-tomcat-8.0.33\temp"
 4 Using JRE_HOME:        "D:\Java\jdk1.8.0_73"
 5 Using CLASSPATH:       "D:\Java\apache-tomcat-8.0.33\bin\bootstrap.jar;D:\Java\apache-tomcat-8.0.33\bin\tomcat-juli.jar"
 6 Connected to the target VM, address: '127.0.0.1:6611', transport: 'socket'
 7 09-Jun-2016 17:58:58.412 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.0.33
 8 09-Jun-2016 17:58:58.416 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Mar 18 2016 20:31:49 UTC
 9 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.0.33.0
10 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Windows 10
11 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            10.0
12 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
13 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             D:\Java\jdk1.8.0_73\jre
14 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.8.0_73-b02
15 09-Jun-2016 17:58:58.417 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
16 09-Jun-2016 17:58:58.418 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         C:\Users\miaorf\.IntelliJIdea2016.1\system\tomcat\Unnamed_spmvtest
17 09-Jun-2016 17:58:58.419 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         D:\Java\apache-tomcat-8.0.33
18 09-Jun-2016 17:58:58.420 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:6611,suspend=y,server=n
19 09-Jun-2016 17:58:58.420 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote=
20 09-Jun-2016 17:58:58.420 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.port=1099
21 09-Jun-2016 17:58:58.420 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.ssl=false
22 09-Jun-2016 17:58:58.421 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.authenticate=false
23 09-Jun-2016 17:58:58.421 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.rmi.server.hostname=127.0.0.1
24 09-Jun-2016 17:58:58.421 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=C:\Users\miaorf\.IntelliJIdea2016.1\system\tomcat\Unnamed_spmvtest\conf\logging.properties
25 09-Jun-2016 17:58:58.422 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
26 09-Jun-2016 17:58:58.422 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.endorsed.dirs=D:\Java\apache-tomcat-8.0.33\endorsed
27 09-Jun-2016 17:58:58.422 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=C:\Users\miaorf\.IntelliJIdea2016.1\system\tomcat\Unnamed_spmvtest
28 09-Jun-2016 17:58:58.422 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=D:\Java\apache-tomcat-8.0.33
29 09-Jun-2016 17:58:58.423 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=D:\Java\apache-tomcat-8.0.33\temp
30 09-Jun-2016 17:58:58.423 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Java\jdk1.8.0_73\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;;D:\Java\jdk1.8.0_73\bin;C:\Program Files (x86)\Skype\Phone\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin;C:\Program Files\Redis\;D:\Java\gradle-2.12\bin;C:\Program Files (x86)\Calibre2\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Samsung\SamsungLink\AllShare Framework DMS\bin\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Samsung\SamsungLink\AllShare Framework DMS\bin\;D:\workspace\springboot\spring-1.4.0.BUILD-SNAPSHOT\bin;D:\Java\apache-maven-3.3.9\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;D:\data\sqlite;.
31 09-Jun-2016 17:58:58.691 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
32 09-Jun-2016 17:58:58.771 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
33 09-Jun-2016 17:58:58.777 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8443"]
34 09-Jun-2016 17:58:59.120 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
35 09-Jun-2016 17:58:59.121 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
36 09-Jun-2016 17:58:59.124 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
37 09-Jun-2016 17:58:59.125 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1454 ms
38 09-Jun-2016 17:58:59.186 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
39 09-Jun-2016 17:58:59.187 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.33
40 09-Jun-2016 17:58:59.202 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
41 09-Jun-2016 17:58:59.218 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8443"]
42 09-Jun-2016 17:58:59.222 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
43 09-Jun-2016 17:58:59.226 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 99 ms

4.测试访问

三 java请求https

采用httpclient4.3+

ssl需要制定证书,这里首先忽略证书访问:

public static HttpClient getClient(boolean isSSL) {
    if (isSSL) {
        try {
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
    }

    return httpclient;
}

Test:

显然,最初设置证书的时候的名字就是域名,于是需要重置证书后重启项目:

结果正常:

 提供keystore:

@Test
    public void testHttpsWithCertification() throws Exception{
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new File("my.keystore"), "123456".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {

            HttpGet httpget = new HttpGet("https://localhost:8443/hello/list");

            System.out.println("Executing request " + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(entity));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏猿天地

spring boot 实现mysql读写分离

如何实现读写分离呢?或者说实现一主多从? 一般我们在项目中配置数据源的时候基本上都是配一个数据库的链接地址,如果要读写分离,意味着要配N个链接地址。 思路其实很...

3188
来自专栏JavaEE

springData Jpa 快速入门前言:一、简介:二、JPA核心概念:三、springboot集成jpa案例:总结:

数据持久化的操作,一般都要由我们自己一步步的去编程实现,mybatis通过我们编写xml实现,hibernate也要配置对应的xml然后通过创建session执...

542
来自专栏技术记录

前端插件——头像截图上传插件的使用(带后台)

效果图:实现上传头像,右边是预览,有三个大小,可以对头像进行裁剪 ? HTML: toParentData 和 img 返回的是图片裁剪后的base64编码。其...

4525
来自专栏潇涧技术专栏

Head First Android Testing 1

最近想写一个自己的库项目,以后开发都基于这个库项目来开发,于是乎,为了保证库项目中的代码功能没有问题,简单学了一些Android测试的内容,对于没有搞过测试的我...

652
来自专栏Gaussic

Spring MVC绑定 List 对象参数 原

       最近做的一个小小的项目碰上了如何用 post 传递一整个 list 的问题,在解决这个问题的同时,也顺带升级一下 Spring 的版本,并精简一下...

541
来自专栏Porschev[钟慰]的专栏

分享一下cookies操作(增、删、改、查)小经验

前段时间在做一个 SSO(Single Sign On),用cookies去存Token 网站保存用户信息这类都用的cookies 以前觉得cookies操作无...

1888
来自专栏Java成神之路

Eclipse插件开发_学习_02_GEF入门实例

(2)搜索 editors,选择 org.eclipse.ui.editors  扩展点,finish

562
来自专栏张善友的专栏

ASP.NET MVC2 数据模型验证类库:MVC Foolproof Validation

MVC Foolproof Validation是一个数据模型类库扩展。 操作符验证 1: public class SignUpViewModel ...

1838
来自专栏Ryan Miao

springmvc4环境简单搭建和定时任务

之前复制粘贴创建了几个ssm的项目,然而回头让自己写的时候还是一头雾水,究其原因是spring的陌生。仅仅是写过几个helloworld而已。而且是照着写。我都...

2184
来自专栏柠檬先生

Angularjs基础(五)

AngularJS Select(选项框)     AngularJS 可是使用数组或对象创建一个下拉列表选项。 使用ng-options创建选项框    ...

1685

扫描关注云+社区