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 ...
随机推荐
- tf.reduce_sum() and tf.where()的用法
import tensorflow as tfimport numpy as npsess=tf.Session()a=np.ones((5,6))c=tf.cast(tf.reduce_sum(a, ...
- Java自学-集合框架 泛型Generic
ArrayList上使用泛型 步骤 1 : 泛型 Generic 不指定泛型的容器,可以存放任何类型的元素 指定了泛型的容器,只能存放指定类型的元素以及其子类 package property; pu ...
- 【设计模式】Singleton
前言 Singleton设计模式,确保全局只存在一个该类的实例.将构造器声明为private,防止调用(虽然还是可以使用反射来调用).声明一个静态的类实例在类中,声明一个公共的获取实例的方法.这篇博文 ...
- PHP基础(谈一谈Session&Cookie)
cookie和sessiond的主要区别 (1).保存位置稍有区别 cookie数据存放在客户的浏览器上,服务器端不用保存.session数据放在服务器上,本地内存也有一份. (2).安全性不同 co ...
- 经典的卷积神经网络及其Pytorch代码实现
1.LeNet LeNet是指LeNet-5,它是第一个成功应用于数字识别的卷积神经网络.在MNIST数据集上,可以达到99.2%的准确率.LeNet-5模型总共有7层,包括两个卷积层,两个池化层,两 ...
- Ubuntu下使用linuxdeployqt打包Qt程序
写了点Qt界面程序,然而发现很难移植到其他没有安装Qt环境的电脑上运行.查资料了解到,在windows上有windeployqt程序,linux上有linuxdeployqt可以帮助我们快速打包. 1 ...
- Ninja——小而快的构建系统
介绍 Ninja 是Google的一名程序员推出的注重速度的构建工具,一般在Unix/Linux上的程序通过make/makefile来构建编译,而Ninja通过将编译任务并行组织,大大提高了构建速度 ...
- 1. jenkins 安装部署
参考文档: https://jenkins.io/zh 准备环境 - jdk 路径: https://www.oracle.com/technetwork/java/javase/a ...
- 201871010121 王方 《面向对象程序设计(JAVA)》第七周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- leetcode14最长公共前缀
class Solution { public: string longestCommonPrefix(vector<string>& strs) { ) return " ...