生成Web自签名的证书(在命令行执行以下命令)

keytool -genkey -keysize 2048 -validity 3650 -keyalg RSA -dname "CN=Hanshow, OU=Hanshow, O=Hanshow, L=Jiaxing, ST=Zhejiang, C=CN" -alias shopweb -keypass password_of_key -storepass password_of_store -keystore shopweb.jks

-keysize 2048 指定生成2048位的密钥

-validity 3650 指定证书有效期天数(3650=10年)

-keyalg RSA 指定用RSA算法生成密钥

-dname 设置签发者的信息

-alias 设置别名

-keypass 设定访问key的password

-storepass 设定访问这个KeyStore的password

web.jks指定生成的KeyStore文件名叫web.jks

  • 把生成的web.jks存放到classpath路径中。
  • 以下代码依赖Jackson JSON,OkHttp3,Apache XML-RPC Client。
  • 以下的实现全部是基于trustAll,即信任任何服务器

基础SSL工具类SSLUtils

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate; public class SSLUtils {
public static KeyStore loadKeyStore(String type, String fileName, String password) throws Exception {
try (InputStream input = SSLUtils.class.getClassLoader().getResourceAsStream(fileName)) {
if (input == null) {
throw new FileNotFoundException(String.format("cannot find KeyStore file \"%s\" in classpath",
fileName));
} KeyStore ks = KeyStore.getInstance(type);
ks.load(input, password.toCharArray());
return ks;
}
} /**
* 创建SSLSocketFactory
*
* @param protocol SSL协议,默认:TLS
* @param algorithm KeyManager算法,默认:SunX509
* @param provider KeyManager提供者,默认:SunJSSE
* @param keyPassword Key password
* @param keyStoreType KeyStore类型,默认:JKS
* @param keyStoreFileName KeyStore文件名,应在classpath中能找到。
* @param storePassword KeyStore的password
* @return SSLSocketFactory实例
* @throws Exception
*/
public static SSLSocketFactory createSSLSocketFactory(String protocol, String algorithm, String provider, String keyPassword,
String keyStoreType, String keyStoreFileName, String storePassword) throws Exception { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm, provider);
KeyStore keyStore = loadKeyStore(keyStoreType, keyStoreFileName, storePassword);
keyManagerFactory.init(keyStore, keyPassword.toCharArray()); TrustManager[] trustManagers = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
} public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Trust always
} public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Trust always
}
}
}; SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers,
new SecureRandom());
return sslContext.getSocketFactory();
} public static SSLSocketFactory createSSLSocketFactory(String keyPassword, String keyStoreFileName, String storePassword) throws Exception {
return createSSLSocketFactory("TLS", "SunX509", "SunJSSE", keyPassword,
"JKS", keyStoreFileName, storePassword); } public static HostnameVerifier createHostnameVerifier() {
return (hostname, session) -> true;
}
}

  XML-RPC Client

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.net.URL; public class DemoXmlRpcClient {
private static boolean SSLContextInitialized = false; private URL url;
private XmlRpcClient xmlRpcClient; public DemoXmlRpcClient(URL url) {
this.url = url;
if ("https".equalsIgnoreCase(url.getProtocol())) {
initSSLContext();
} XmlRpcClientConfigImpl rpcConfig = new XmlRpcClientConfigImpl();
rpcConfig.setServerURL(this.url);
// 设置RPC连接超时时间为60秒
rpcConfig.setConnectionTimeout(60 * 1000);
// 设置RPC等待响应时间为60秒
rpcConfig.setReplyTimeout(60 * 1000);
this.xmlRpcClient = new XmlRpcClient();
this.xmlRpcClient.setConfig(rpcConfig);
} private synchronized void initSSLContext() {
if (!SSLContextInitialized) { // 只需要初始化一次
try {
SSLSocketFactory sslSocketFactory = SSLUtils.createSSLSocketFactory(
"password_of_key", "shopweb.jks", "password_of_store");
HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
} catch (Throwable t) {
throw new RuntimeException("initialize SSLContext for XML-RPC error", t);
}
SSLContextInitialized = true;
}
} public Object execute(String command, Object[] params) throws Exception {
return xmlRpcClient.execute(command, params);
} public URL getUrl() {
return url;
} public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Object response; // 测试通过HTTPS向ESL-Working发送XML-RPC请求
DemoXmlRpcClient sslClient = new DemoXmlRpcClient(new URL("https://127.0.0.1:9443/RPC2"));
response = sslClient.execute("send_cmd", new Object[]{"API_VERSION", new Object[]{}});
System.out.println(objectMapper.writeValueAsString(response)); // 测试通过HTTP向ESL-Working发送XML-RPC请求
DemoXmlRpcClient normalClient = new DemoXmlRpcClient(new URL("http://127.0.0.1:9000/RPC2"));
response = normalClient.execute("send_cmd", new Object[]{"API_VERSION", new Object[]{}});
System.out.println(objectMapper.writeValueAsString(response));
}
}

HTTP Client

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.platform.Platform; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit; public class DemoHttpClient {
private final static String JSON_MEDIA_TYPE_PATTERN = "application/json; charset=%s";
private final static String DEFAULT_CHARSET = "utf-8";
private final static String DEFAULT_CONTENT_TYPE = String.format(JSON_MEDIA_TYPE_PATTERN, DEFAULT_CHARSET); private final static ObjectMapper objectMapper = new ObjectMapper();
private OkHttpClient httpClient;
private OkHttpClient httpsClient; public DemoHttpClient(String keyPassword, String fileName, String storePassword) throws Exception {
httpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS).build(); SSLSocketFactory sslSocketFactory = SSLUtils.createSSLSocketFactory(keyPassword, fileName, storePassword);
X509TrustManager x509TrustManager = Platform.get().trustManager(sslSocketFactory);
httpsClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.sslSocketFactory(sslSocketFactory, x509TrustManager)
.hostnameVerifier(SSLUtils.createHostnameVerifier())
.build();
} public String get(String url) throws IOException {
return get(new URL(url));
} public String get(URL url) throws IOException {
return httpRequest(url, "GET", DEFAULT_CONTENT_TYPE, null);
} public String post(String url, Object data) throws IOException {
return post(new URL(url), data);
} public String post(URL url, Object object) throws IOException {
byte[] data = objectMapper.writeValueAsString(object).getBytes(DEFAULT_CHARSET);
return httpRequest(url, "POST", DEFAULT_CONTENT_TYPE, data);
} public String put(String url, Object data) throws IOException {
return put(new URL(url), data);
} public String put(URL url, Object object) throws IOException {
byte[] data = objectMapper.writeValueAsString(object).getBytes(DEFAULT_CHARSET);
return httpRequest(url, "PUT", DEFAULT_CONTENT_TYPE, data);
} public String httpRequest(URL url, String method, String contentType, byte[] data) throws IOException {
OkHttpClient client;
String protocol = url.getProtocol();
if ("http".equalsIgnoreCase(protocol)) {
client = httpClient;
} else if ("https".equalsIgnoreCase(protocol)) {
client = httpsClient;
} else {
throw new UnsupportedOperationException("unsupported protocol: " + protocol);
} Request.Builder builder = new Request.Builder().url(url);
MediaType mediaType = MediaType.parse(contentType);
if ("GET".equalsIgnoreCase(method)) {
builder.get();
} else {
RequestBody requestBody = RequestBody.create(mediaType, data == null ? new byte[0] : data);
builder.method(method, requestBody);
} Request request = builder.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
ResponseBody responseBody = response.body();
return responseBody == null ? null : responseBody.string();
} else {
throw new IOException(String.format(
"%s/%s %s got unexpected response code %d",
protocol.toUpperCase(), method, url, response.code()));
}
}
} public static void main(String[] args) throws Exception {
DemoHttpClient httpClient = new DemoHttpClient("password_of_key", "shopweb.jks", "password_of_store"); // 通过HTTP访问ESL-Working RESTful接口
System.out.println(httpClient.get("http://127.0.0.1:9000/api2/runinfo")); // 通过HTTPS访问ESL-Working RESTful接口
System.out.println(httpClient.get("https://127.0.0.1:9443/api2/runinfo"));
}
}

  

Web支持HTTPS的client(HTTP&XML-RPC)的更多相关文章

  1. Web API应用支持HTTPS的经验总结

    在我前面介绍的WebAPI文章里面,介绍了WebAPI的架构设计方面的内容,其中提出了现在流行的WebAPI优先的路线,这种也是我们开发多应用(APP.微信.微网站.商城.以及Winform等方面的整 ...

  2. 实现KbmMw web server 支持https

    在以前的文章里面介绍过kbmmw 做web server. 前几天红鱼儿非要我给他做一个支持https 的web server. 其实kbmmw 支持https 有好几种方法: 1. 使用isapi ...

  3. web开发必看:你的网站支持https吗?

    如果有一项技术可以让网站的访问速度更快.更安全.并且seo权重提升(百度除外),而且程序员不需要改代码就可以全站使用,最重要的是,不需要额外花钱,那有这么好的事情吗? HTTP通信协议是全球万维网ww ...

  4. 在iOS APP中使用H5显示百度地图时如何支持HTTPS?

    现象: 公司正在开发一个iOSAPP,使用h5显示百度地图,但是发现同样的H5页面,在安卓可以显示出来,在iOS中就显示不出来. 原因分析: 但是现在iOS开发中,苹果已经要求在APP中的所有对外连接 ...

  5. iOS支持Https

    http://oncenote.com/2014/10/21/Security-1-HTTPS/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_s ...

  6. 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化

    谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...

  7. https大势已来?看腾讯专家如何在高并发压测中支持https

    WeTest 导读 用epoll编写一个高并发网络程序是很常见的任务,但在epoll中加入ssl层的支持则是一个不常见的场景.腾讯WeTest服务器压力测产品,在用户反馈中收到了不少支持https协议 ...

  8. 支持https的压力测试工具

    支持https的压力测试工具 测试了linux下的几种压力测试工具,发现有些不支持https,先简单总结如下: 一.apache的ab工具 /home/webadm/bin/ab -c 50 -n 1 ...

  9. Retrofit 2.0 超能实践(一),okHttp完美支持Https传输

    http: //blog.csdn.net/sk719887916/article/details/51597816 Tamic首发 前阵子看到圈子里Retrofit 2.0,RxJava(Andro ...

随机推荐

  1. Python【day 11】迭代器

    迭代器-用 1.迭代器的概念 1.可迭代对象-iterable str.list.tuple.dict.set.open().range() 2.可迭代对象的概念: 其数据类型的执行方法中含有__it ...

  2. codeforces #579(div3)

    codeforces #579(div3) A. Circle of Students 题意: 给定一个n个学生的编号,学生编号1~n,如果他们能够在不改变顺序的情况下按编号(无论是正序还是逆序,但不 ...

  3. Vue计算属性computed的全面解析

    前言 一直以来对computed这个计算属性都只停在一个大概的认知中,最近特意仔细研读相关资料,亲测后逐渐了解了其特性. 正文 computed 特点: 1.初始化/依赖属性(即data属性)改变时执 ...

  4. SAP 公司间STO场景中外向交货单过账后自动触发内向交货单功能的实现

    SAP 公司间STO场景中外向交货单过账后自动触发内向交货单功能的实现 如下STO,是从公司代码SZSP转入CSAS, 如下图示的内向交货单180018660.该内向交货单是在外向交货单8001632 ...

  5. AI人脸识别的测试重点

    最常见的 AI应用就是人脸识别,因此这篇文章从人脸识别的架构和核心上,来讲讲测试的重点. 测试之前需要先了解人脸识别的整个流程,红色标识代表的是对应AI架构中的各个阶段 首先是人脸采集. 安装拍照摄像 ...

  6. git tag介绍

    我们常常在代码发版时,使用git 创建一个tag ,这样一个不可修改的历史代码版本就像被我们封存起来一样,不论是运维发布拉取,或者以后的代码版本管理,都是十分方便的. git的tag功能git 下打标 ...

  7. pipenv管理python开发环境

    简介 简单说,pipenv就是把pip和virtualenv包装起来的一个便携工具. 它不会在你的项目文件夹里生成一大堆东西,只有两个文本文件: Pipfile, 简明地显示项目环境和依赖包. Pip ...

  8. odoo10学习笔记十六:定时任务

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/11189382.html 一:定义定时器数据模型 模型中定义需要用到的字段.定时方法 from odoo im ...

  9. 8、RabbitMQ三种Exchange模式(fanout,direct,topic)的性能比较

    RabbitMQ三种Exchange模式(fanout,direct,topic)的性能比较 RabbitMQ中,除了Simple Queue和Work Queue之外的所有生产者提交的消息都由Exc ...

  10. Git学习笔记2-版本控制

    1.移除文件 第一步: $ git rm <flie> #删除工作区以及仓库里面的文件 $ git rm <flie> -f #如果文件删除之前修改过并且已经存放到暂存区域,使 ...