问题描述
在开发过程中使用绝对路径访问ca证书文件,结果打成jar包后,发生了 no such file or dictionary 的异常
解决方法
使用
String certPath = this.getClass().getResource("/${name}").getPath();
java中jar包内的类访问jar包内部的资源文件的路径问题
来获取路径时,得到的路径是
!BOOT-INF/Classes!/${name}
仍然会造成找不到文件的问题
出现!BOOT-INF/Classes!/${name}路径的解释
以流(stream)的方式读取资源,然后用于创建SSLContext 对象,才解决
public SSLContext doCustom(InputStream ins,String keyStorepass){
SSLContext sc = null;
KeyStore trustStore = null;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(ins, keyStorepass.toCharArray());
sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | KeyManagementException e) {
e.printStackTrace();
} finally {
try {
ins.close();
} catch (IOException e) {
}
}
return sc;
}
public String doPostJsonObj(String url, String json){
KeyStore trustStore = null;
InputStream certStream = this.getClass().getResourceAsStream("/${certName}");
HttpSSLClientUtil httpsClient = new HttpSSLClientUtil();
SSLContext sslcontext = httpsClient.doCustom(certStream, "${pwd}");
SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslcontext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslcsf).build();
CloseableHttpResponse response=null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}