最近调试微信接口模拟使用SSL证书方式访问微信接口,苦于没有测试证书,故多方查找资料后,找到使用java生成证书可以满足使用要求。具体如下(还可生成其它格式证书文件):
进入java的bin目录执行以下命令即可生成证书。
keytool -genkey -alias 别名 -keypass 密码 -keyalg RSA -keysize 2048 -validity 365 -keystore 文件路径/文件名.p12 -storepass 密码 -deststoretype pkcs12
keytool -genkey -alias 别名 -keypass 密码 -keyalg RSA -keysize 2048 -validity 365 -keystore 文件路径/文件名.p12 -storepass 密码 -deststoretype pkcs12
《以下无关》
public static void main(String[] args) throws Exception {
String cert = "读取p12文件然后base64";
String pwd = "p12证书密码";
char[] password = pwd.toCharArray();
byte[] certBytes = Base64.decode(cert);
ByteArrayInputStream certStream = new ByteArrayInputStream(certBytes);
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certStream, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1"},
null,
new DefaultHostnameVerifier());
BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build(),
null,
null,
null
);
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(10000)
.setConnectTimeout(1000)
.setSocketTimeout(5000).build())
.setConnectionManager(connectionManager) //不与其他HttpClient共享连接池
.evictExpiredConnections() //回收过期连接
.setRetryHandler(new DefaultHttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount > 3) {
return false;
}
if (exception instanceof NoHttpResponseException) {
return true;
}
return super.retryRequest(exception, executionCount, context);
}
}).build();
}