Jersey框架三:Jersey对HTTPS的支持
Jersey系列文章:
Jersey框架一:Jersey RESTful WebService框架简介
证书的生成过程这里就不介绍了,请参照:Java网络编程二:Java Secure(SSL/TLS) Socket实现中的证书部分
代码结构如下:
Maven配置文件:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JERSEY</groupId>
<artifactId>JERSEY</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.15</version>
</dependency>
</dependencies>
</project>
Person类是基本的JAXB:
package com.sean; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement
public class Person {
private String name;
private List<String> addresses; public Person(){} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public List<String> getAddresses() {
return addresses;
} public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
}
客户端代码:
package com.sean; import java.net.URI; import javax.net.ssl.SSLContext;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder; import org.glassfish.jersey.SslConfigurator; import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties; public class SSLClient {
public static void main(String[] args) {
int authType =
Integer.valueOf(Config.getConfig().getProperty("authority")).intValue(); SslConfigurator sslConfig = SslConfigurator.newInstance();
if(authType == 1){
sslConfig.trustStoreFile(Config.getConfig().getProperty("clientTrustCer"))
.trustStorePassword(Config.getConfig().getProperty("clientTrustCerPwd"));
}else if(authType == 2){
sslConfig.keyStoreFile(Config.getConfig().getProperty("clientCer"))
.keyStorePassword(Config.getConfig().getProperty("clientCerPwd"))
.keyPassword(Config.getConfig().getProperty("clientKeyPwd"))
.trustStoreFile(Config.getConfig().getProperty("clientTrustCer"))
.trustStorePassword(Config.getConfig().getProperty("clientTrustCerPwd"));
}
sslConfig.securityProtocol(Config.getConfig().getProperty("protocol"));
SSLContext sslContext = sslConfig.createSSLContext(); ClientConfig cc = new DefaultClientConfig();
cc.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties(new MyHostnameVerifier(), sslContext));
Client client = Client.create(cc); URI uri = UriBuilder.fromUri("https://127.0.0.1/queryAddress").port(10000).build();
WebResource resource = client.resource(uri); Person person = new Person();
person.setName("sean"); ClientResponse response = resource
.accept(MediaType.APPLICATION_XML)
.type(MediaType.APPLICATION_XML)
.post(ClientResponse.class, person); String addresses = response.getEntity(String.class);
System.out.println(addresses);
}
}
SSL握手过程中,会对请求IP或请求域名进行校验,如果在证书信息中无法找到相关请求IP或请求域名则会报错(javax.NET.ssl.SSLHandshakeException: Java.security.cert.CertificateException: No subject alternative names present)
这里实现自己的校验逻辑(如果请求的IP为127.0.0.1或请求的域名为localhost,则直接通过校验)以覆盖默认逻辑
package com.sean; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession; public class MyHostnameVerifier implements HostnameVerifier { @Override
public boolean verify(String hostname, SSLSession session) {
if("127.0.0.1".equals(hostname) || "localhost".equals(hostname) )
return true;
else
return false;
}
}
服务端代码:
package com.sean; import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List; import javax.net.ssl.SSLContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder; import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.jersey.SslConfigurator; import com.sun.jersey.api.container.ContainerFactory;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig; @Path("queryAddress")
public class SSLServer { @POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Person queryAddress(String name) {
System.out.println(name); Person person = new Person();
List<String> addresses = new ArrayList<String>();
addresses.add("address1");
addresses.add("address2");
person.setAddresses(addresses);
return person;
} public static void main(String[] args) {
Integer authType =
Integer.valueOf(Config.getConfig().getProperty("authority")).intValue(); SslConfigurator sslConfig = SslConfigurator.newInstance();
if(authType == 1){
sslConfig.keyStoreFile(Config.getConfig().getProperty("serverCer"))
.keyStorePassword(Config.getConfig().getProperty("serverCerPwd"))
.keyPassword(Config.getConfig().getProperty("serverKeyPwd"));
}else if(authType == 2){
sslConfig.keyStoreFile(Config.getConfig().getProperty("serverCer"))
.keyStorePassword(Config.getConfig().getProperty("serverCerPwd"))
.keyPassword(Config.getConfig().getProperty("serverKeyPwd"))
.trustStoreFile(Config.getConfig().getProperty("serverTrustCer"))
.trustStorePassword(Config.getConfig().getProperty("serverTrustCerPwd"));
}
sslConfig.securityProtocol(Config.getConfig().getProperty("protocol"));
SSLContext sslContext = sslConfig.createSSLContext(); SSLEngineConfigurator sslEngineConfig = new SSLEngineConfigurator(sslContext);
//默认情况下是客户端模式,如果忘记修改模式
//会抛出异常
//javax.net.ssl.SSLProtocolException: Handshake message sequence violation, 1]
sslEngineConfig.setClientMode(false);
if(authType == 1)
sslEngineConfig.setWantClientAuth(true);
else if(authType == 2)
sslEngineConfig.setNeedClientAuth(true); ResourceConfig rc = new PackagesResourceConfig("com.sean");
HttpHandler handler = ContainerFactory.createContainer(
HttpHandler.class, rc); URI uri = UriBuilder.fromUri("https://127.0.0.1/").port(10000).build();
try {
HttpServer server = GrizzlyServerFactory.createHttpServer(uri, handler, true,
sslEngineConfig);
server.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
配置文件类:
package com.sean; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties; public class Config{
private static Properties config; public static Properties getConfig(){
try{
if(null == config){
File configFile =
new File("src/main/resources/config/config.properties");
if(configFile.exists() && configFile.isFile()
&& configFile.canRead()){
InputStream input = new FileInputStream(configFile);
config = new Properties();
config.load(input);
}
}
}catch(Exception e){
//default set
config = new Properties();
config.setProperty("authority", String.valueOf(1));
config.setProperty("protocol", "SSL");
config.setProperty("serverCer", "src/main/resources/certificate/server.jks");
config.setProperty("serverCerPwd", "1234sp");
config.setProperty("serverKeyPwd", "1234kp");
config.setProperty("serverTrustCer", "src/main/resources/certificate/serverTrust.jks");
config.setProperty("serverTrustCerPwd", "1234sp");
config.setProperty("clientCer", "src/main/resources/certificate/client.jks");
config.setProperty("clientCerPwd", "1234sp");
config.setProperty("clientKeyPwd", "1234kp");
config.setProperty("clientTrustCer", "src/main/resources/certificate/clientTrust.jks");
config.setProperty("clientTrustCerPwd", "1234sp");
}
return config;
}
}
配置文件config.properties:
#1:单向认证,只有服务器端需证明其身份
#2:双向认证,服务器端和客户端都需证明其身份
authority=2
#通信协议
protocol=SSL
#服务端证书信息
serverCer=src/main/resources/certificate/server.jks
#keystore的storepass
serverCerPwd=1234sp
#keystore的keypass
serverKeyPwd=1234kp
#服务端证书信息
serverTrustCer=src/main/resources/certificate/serverTrust.jks
serverTrustCerPwd=1234sp
#客户端证书信息
clientCer=src/main/resources/certificate/client.jks
clientCerPwd=1234sp
clientKeyPwd=1234kp
clientTrustCer=src/main/resources/certificate/clientTrust.jks
clientTrustCerPwd=1234sp
服务端运行结果:
三月 03, 2015 3:30:54 下午 com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
com.sean
三月 03, 2015 3:30:54 下午 com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
class com.sean.SSLServer
三月 03, 2015 3:30:54 下午 com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
三月 03, 2015 3:30:54 下午 com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.18 11/22/2013 01:21 AM'
三月 03, 2015 3:30:55 下午 org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [127.0.0.1:10000]
三月 03, 2015 3:30:55 下午 org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><name>sean</name></person>
客户端运行结果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><addresses>address1</addresses><addresses>address2</addresses></person>
Jersey框架三:Jersey对HTTPS的支持的更多相关文章
- Jersey框架二:Jersey对JSON的支持
Jersey系列文章: Jersey框架一:Jersey RESTful WebService框架简介 Jersey框架二:Jersey对JSON的支持 Jersey框架三:Jersey对HTTPS的 ...
- Jersey框架一:Jersey RESTful WebService框架简介
Jersey系列文章: Jersey框架一:Jersey RESTful WebService框架简介 Jersey框架二:Jersey对JSON的支持 Jersey框架三:Jersey对HTTPS的 ...
- Java Restful框架:Jersey入门示例(官方例子)
本文主要介绍了Java Restful框架Jersey入门例子(来源于官方网站https://jersey.java.net/),废话不多说进入正题. 在Jersey官方示例中(https://jer ...
- jersey框架实现文件上传
jersey框架是一个开源的RESTful的框架,实现了实现了JAX-RS规范,进一步地简化 RESTful service 和 client 开发.当然而且是必须的,jersey对文件的上传和下载也 ...
- Equinox OSGi应用嵌入Jersey框架搭建REST服务
原文地址:https://www.cnblogs.com/kira2will/p/5040264.html 一.环境 eclipse版本:eclipse-luna 4.4 jre版本:1.8 二.Eq ...
- Oltu在Jersey框架上实现oauth2.0授权模块
oltu是一个开源的oauth2.0协议的实现,本人在此开源项目的基础上进行修改,实现一个自定义的oauth2.0模块. 关于oltu的使用大家可以看这里:http://oltu.apache.org ...
- 关于Jersey框架下的Aop日志 和Spring 框架下的Aop日志
摘要 最近新接手的项目经常要查问题,但是,前面一拨人,日志打的非常乱,好多就根本没有打日志,所以弄一个AOP统一打印一下 请求数据和响应数据 框架 spring+springmvc+jersey 正文 ...
- 原创:Equinox OSGi应用嵌入Jersey框架搭建REST服务
一.环境 eclipse版本:eclipse-luna 4.4 jre版本:1.8 二.Equinox OSGi应用嵌入Jersey框架搭建REST服务 1.新建插件工程HelloWebOSGI a. ...
- 如何解决jersey框架中以json格式返回数组,当数组中元素一个时json格式不对
原文地址:http://www.cnblogs.com/swpk/p/3566536.html?utm_source=tuicool jersey 是oracle 出的一个较好的REST框架.使用此框 ...
随机推荐
- arm-linux-gcc下载与安装
在RHEL 5平台上安装配置arm-linux-gcc 2011-02-23 19:35:40| 分类: 嵌入式开发环境 | 标签: |字号大中小 订阅 . 在linux平台上安装好的基础上,开 ...
- 性能测试之LoardRunner工作原理
概述: 1.VuGen 2.控制器 3.负载发生器 4.分析器 VuGen,它的作用是捕捉用户的业务流,并最终将其录制成一个脚本.在录制脚本前首先选择一种协议,接着在客户端模拟客户实际使用过程中的业务 ...
- 【学习opencv第七篇】图像的阈值化
图像阈值化的基本思想是,给定一个数组和一个阈值,然后根据数组中每个元素是低于还是高于阈值而进行一些处理. cvThreshold()函数如下: double cvThreshold( CvArr* s ...
- 页面爬虫(获取其他页面HTML)加载到自己页面
//前台 <div id="showIframe"></div> $(document).ready(function() { var url = &quo ...
- 【每日一摩斯】-Troubleshooting: High CPU Utilization (164768.1) - 系列4
Jobs (CJQ0, Jn, SNPn) Job进程运行用户定义的以及系统定义的类似于batch的任务.检查Job进程占用大量CPU资源的方法,就像检查用户进程一样. 可以根据以下视图检查Job进程 ...
- Swift - 跑酷游戏开发(SpriteKit游戏开发)
一,下面演示了如何开发一个跑酷游戏,实现的功能如下: 1,平台工厂会不断地生成平台,并且向左移动.当平台移出游戏场景时就可将其移除. 2,生成的平台宽度随机,高度随机.同时短平台踩踏的时候会下落. 3 ...
- python实现刷博器(适用于新浪、搜狐)
本文总结于智普教育: 做点小东西,有成就感,才会有动力学下去哈! 先上代码: 1: import webbrowser as web 2: import time 3: import os 4: co ...
- 14.8.2 Verifying File Format Compatibility 校验文件格式兼容性:
14.8.2 Verifying File Format Compatibility 校验文件格式兼容性: 14.8.2.1 Compatibility Check When InnoDB Is St ...
- uva 657
很简单的题,就是题意不懂……! 就是判断每个'*'区域内‘X’区域块的个数 WA了好多次,就是太差了: 1.结果排序输出 2.因为是骰子所以不再1-6范围内的数字要舍弃 3.格式要求要空一行…… 4. ...
- 关键部分CCriticalSection使用
类CCriticalSection的对象表示一个“临界区”,它是一个用于同步的对象,同一时刻仅仅同意一个线程存取资源或代码区.临界区在控制一次仅仅有一个线程改动数据或其他的控制资源时很实用.比如,在链 ...