生成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. c# 模拟表单提交,post form 上传文件、数据内容

    转自:https://www.cnblogs.com/DoNetCShap/p/10696277.html 表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipar ...

  2. 利用Java EE里jsp制作登录界面

    jsp连接数据库.百度经验. 1.在新建的Project中右键新建Floder 2.创建名为lib的包 3.创建完毕之后的工程目录 4.接下来解压你下载的mysql的jar包,拷贝其中的.jar文件 ...

  3. var变量

    # Aduthor:CCIP-Ma name = "ma" name2 = name name = "ccip-ma" print("My name ...

  4. Android四大组件:BroadcastReceiver 介绍

    介绍 BroadcastReceiver 即广播组件,是 Android 的四大组件之一.用于监听和接收广播消息,并做出响应.有以下一些应用: 不同组件之间的通信(应用内或不同应用之间). 多线程之间 ...

  5. Android软件架构

    08_29_Android软件架构 架构的本质 本质, 类似图纸, 不是建筑物: 明确范围 软件设计中, 架构不等于框架: 底层的编码,到设计模式, 到框架,再到架构(微服务,SOA) 好的架构 做好 ...

  6. updataStateByKey算子的使用

    updataStateByKeyApp.scala import org.apache.spark.SparkConf import org.apache.spark.streaming.{Secon ...

  7. 关于SQLite数据库 字段 DateTime 类型

    这两天刚接触SQLite 数据库 还没有太过于深入的了解 , 于是出现了一个问题 : 我在 C#中 ,使用SQLiteHelper 查询SQLite数据库数据时,报了这个错误: System.Form ...

  8. CSS3 边框 border-image

    border-image:xx xx xx 是一系列参数的简写,该属性将图片作为边框修饰 border-image-source:url(border.png); 图片url地址 border-ima ...

  9. computed和watch的用法和区别

    computed可以监听v-model(data)中的值,只要值发生变化 他就会重新去计算 computed必须是要有一个返回值的哦 <div id="app"> &l ...

  10. 201871010118-唐敬博《面向对象程序设计(java)》第十六周学习总结

    博文正文开头格式:(2分) 项目 内容 这个作业属于哪个课程 <https://www.cnblogs.com/nwnu-daizh/> 这个作业的要求在哪里 <https://ww ...