当我们应用程序访问设有https证书的服务时,若JRE未安装指定证书则会提示标题的报错,此时有两种方式解决该问题:
按照实际场景,可从信息科、网络处等部门协调获取证书,也可以直接从安装证书的电脑上,通过浏览器下载证书,本文介绍后一种方式。
使用浏览器访问对应的网站例如 百度(www.baidu.com)
点击网址前的小锁子,再点击 "连接是安全的",再点击"证书有效",此时会弹出下列弹窗。
选择详细信息,点击复制到文件
选择需要的证书格式,一般选择第二种 Base64 + CER,然后选择路径导出即可
把证书复制到 jre 路径下,即保证证书与keytool.exe文件同目录。
此时需要注意,一定要确定服务器使用的是单独的jre还是JDK目录下的jre,笔者使用的办法是启动服务后尝试删除其中一个jre文件夹,若提示正在使用则为当前jre生效......
可能有的读者环境会存在都占用的问题,那就只能是两个 jre 目录都导入该证书了,雨露均沾
在keytool.exe目录下打开cmd窗口,执行以下命令
keytool -import -alias baidu -file babidu.cer -keystore "%JAVA_HOME%/jre/lib/security/cacerts"
--提示输入密码,默认密码为 changeit
--提示:“是否信任此证书? [否]:” ,那么请输入"y"。
至此,该证书已导入
本文以Java代码为例,在应用程序访问目标https网址前,增加忽略HTTPS请求
需要注意的是,该忽略方法必须在创建URL连接前执行,示例代码在文末
package com.aikes.mcpc.datauploadlog.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.aikes.common.SslUtils;
import org.apache.log4j.Logger;
public class HttpCilentUtil {
static Logger logger = Logger.getLogger(HttpCilentUtil.class);
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
SslUtils.ignoreSsl(); // 忽略SSL证书验证
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type","application/json");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param SecretKey 加密字符串
* @param requestData 请求数据
* @param Appid 医院ID
* @return 所代表远程资源的响应结果
* @throws Exception
*/
public static String sendPost(String URL,String SecretKey,String Appid,String requestData) throws Exception {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
Date currentTime = new Date();
String time = formatter.format(currentTime);
String requestId = UUID.randomUUID().toString();
//生成签名字符串
String sign = HMACSHA256Util.sha256_HMAC((time+requestId).toUpperCase(), SecretKey);
try {
SslUtils.ignoreSsl(); // 忽略SSL证书验证
// 打开和URL之间的连接
URL realUrl = new URL(URL);
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性;
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("time", time);
conn.setRequestProperty("appId", Appid);
conn.setRequestProperty("requestId", requestId);
conn.setRequestProperty("sign", sign);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
// 发送请求参数
out.print(requestData);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));//指定以UTF-8编码方式读取数据
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
throw new Exception(e.getLocalizedMessage());
}finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
package com.aikes.common;
import javax.net.ssl.SSLContext;
import java.security.cert.X509Certificate;
@SuppressWarnings({"Convert2Lambda"})
public class SslUtils {
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
@SuppressWarnings({"unused", "RedundantThrows"})
static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
}
}
/**
* 忽略SSL证书校验
* @throws Exception e
*/
public static void ignoreSsl() throws Exception {
javax.net.ssl.HostnameVerifier hv = new javax.net.ssl.HostnameVerifier() {
public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {
return true;
}
};
trustAllHttpsCertificates();
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}