Web支持HTTPS的client(HTTP&XML-RPC)
生成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)的更多相关文章
- Web API应用支持HTTPS的经验总结
在我前面介绍的WebAPI文章里面,介绍了WebAPI的架构设计方面的内容,其中提出了现在流行的WebAPI优先的路线,这种也是我们开发多应用(APP.微信.微网站.商城.以及Winform等方面的整 ...
- 实现KbmMw web server 支持https
在以前的文章里面介绍过kbmmw 做web server. 前几天红鱼儿非要我给他做一个支持https 的web server. 其实kbmmw 支持https 有好几种方法: 1. 使用isapi ...
- web开发必看:你的网站支持https吗?
如果有一项技术可以让网站的访问速度更快.更安全.并且seo权重提升(百度除外),而且程序员不需要改代码就可以全站使用,最重要的是,不需要额外花钱,那有这么好的事情吗? HTTP通信协议是全球万维网ww ...
- 在iOS APP中使用H5显示百度地图时如何支持HTTPS?
现象: 公司正在开发一个iOSAPP,使用h5显示百度地图,但是发现同样的H5页面,在安卓可以显示出来,在iOS中就显示不出来. 原因分析: 但是现在iOS开发中,苹果已经要求在APP中的所有对外连接 ...
- iOS支持Https
http://oncenote.com/2014/10/21/Security-1-HTTPS/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_s ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- https大势已来?看腾讯专家如何在高并发压测中支持https
WeTest 导读 用epoll编写一个高并发网络程序是很常见的任务,但在epoll中加入ssl层的支持则是一个不常见的场景.腾讯WeTest服务器压力测产品,在用户反馈中收到了不少支持https协议 ...
- 支持https的压力测试工具
支持https的压力测试工具 测试了linux下的几种压力测试工具,发现有些不支持https,先简单总结如下: 一.apache的ab工具 /home/webadm/bin/ab -c 50 -n 1 ...
- Retrofit 2.0 超能实践(一),okHttp完美支持Https传输
http: //blog.csdn.net/sk719887916/article/details/51597816 Tamic首发 前阵子看到圈子里Retrofit 2.0,RxJava(Andro ...
随机推荐
- J2EE的13种规范
1.JDBC(Java Databaes Connectivity):JDBC API为访问不同的数据库提供了一种统一的途径,就像ODBC一样,JDBC对开发者屏蔽了一些细节问题,同时,JDBC对数据 ...
- 一文让你读懂Synchronized底层实现,秒杀面试官
本文为死磕Synchronized底层实现第三篇文章,内容为轻量级锁实现. 轻量级锁并不复杂,其中很多内容在偏向锁一文中已提及过,与本文内容会有部分重叠. 另外轻量级锁的背景和基本流程在概论中已有讲解 ...
- 安装Yapi时,出现json-schema-faker模块找不到问题
今天换了一台机器按以前的方式安装Yapi工具时,竟然出现了错误. 一 安装yapi时,出现了下面的报错,一开始以为没安装json-schema-faker模块.后面通过找资料,发现是权限问题, 使用c ...
- 【设计模式】Singleton
前言 Singleton设计模式,确保全局只存在一个该类的实例.将构造器声明为private,防止调用(虽然还是可以使用反射来调用).声明一个静态的类实例在类中,声明一个公共的获取实例的方法.这篇博文 ...
- SVG撑满页面
当viewBox属性固定,默认修改svg标签的宽高,svg都会按比例缩放 我们现在不想按比例缩放,需要svg撑满整个画面 这里只需为svg标签添加一个关键属性:preserveAspectRatio ...
- SQLi-LABS Page-1(Basic Challenges) Less1-Less4
Less-1 GET - Error based - Single quotes - Stri http://10.10.202.112/sqli/Less-1?id=1 http://10.10.2 ...
- 通过MES技术居然可以防止制造数据造假?
近些年来我们经历了太多制造数据造假事件,特别是前段时间曝出的医药制造事件更是将我们群众的愤怒值推到了最高点.不过我们最应当做的是,冷静下来,思考一下各行各业的我们是不是都该做些什么了?毕竟当下一个灾难 ...
- libtool编译
1.充分利用共享库的能力.libtool 是一个通用库支持脚本 2.我们可以认为libtool是gcc的一个抽象,也就是说,它包装了gcc或者其他的任何编译器,用户无需知道细节,只要告诉libtool ...
- 奇怪的ifcfg-eth0被自动还原
最近,一台虚拟机是从外网下载的,然后导入本地测试环境使用. 发现一个奇怪的问题:修改了 /etc/sysconfig/network-scripts/ifcfg-eth0 保存后, 重启网络服务( s ...
- 2-1Numpy概述
In [1]: import numpy as np In [2]: array=[1,2,3,4,5] array+1#没定义成numpy.ndarray类型是不能直接操作的 --------- ...