import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
// 检查客户端证书
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
// 检查服务器端证书
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
// 返回受信任的X509证书数组
return null;
}
}
X509证书信任管理器类
public static String httpPostUtil(String pathUrl, JSONObject content) {
boolean isHttps = true;
String strResult = "";
DataOutputStream out = null;
BufferedReader reader = null;
if(pathUrl.toLowerCase().startsWith("https:")){
isHttps = true;
}else{
isHttps = false;
}
if(isHttps){
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new MyX509TrustManager() }, new SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
SSLSocketFactory ssf = ctx.getSocketFactory();
HttpsURLConnection httpsConn = null;
try{
URL url = new URL(pathUrl);
httpsConn = (HttpsURLConnection) url.openConnection();
httpsConn.setSSLSocketFactory(ssf);
httpsConn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
httpsConn.setRequestMethod("POST");
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);
httpsConn.setConnectTimeout(6000);
httpsConn.setReadTimeout(6000);
httpsConn.setRequestProperty("Connection", "keep-alive"); //设置连接的状态
httpsConn.setRequestProperty("Transfer-Encoding", "chunked");//设置传输编码
httpsConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
out = new DataOutputStream(httpsConn.getOutputStream());
out.write(content.toString().getBytes("UTF-8"));
out.flush();
out.close();
StringBuffer stringbuffer = new StringBuffer();
if (httpsConn.getResponseCode()==200){
reader = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
String line="";
while ((line = reader.readLine()) != null) {
stringbuffer.append(line);
}
strResult = stringbuffer.toString();
reader.close();
}else{
}
httpsConn.disconnect();
}catch (Exception e) {
// TODO: handle exception
if(httpsConn!=null){
httpsConn.disconnect();
}
}
}else{
URL postUrl = null;
HttpURLConnection connection = null;
try {
postUrl = new URL(pathUrl);
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);// http正文内,因此需要设为true, 默认情况下是false;
connection.setDoInput(true);
connection.setConnectTimeout(6000);
connection.setReadTimeout(6000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Transfer-Encoding", "chunked");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
out = new DataOutputStream(connection.getOutputStream());
out.write(content.toString().getBytes("UTF-8"));
out.flush();
out.close();
StringBuffer stringbuffer = new StringBuffer();
if (connection.getResponseCode()==200){
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line="";
while ((line = reader.readLine()) != null) {
stringbuffer.append(line);
}
strResult = stringbuffer.toString();
reader.close();
}else{
}
connection.disconnect();
} catch (MalformedURLException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
if(connection!=null){
connection.disconnect();
}
}catch (IOException e3) {
e3.printStackTrace();
if(connection!=null){
connection.disconnect();
}
}
}
logger.info("strResult="+strResult);
return strResult;
}
生成证书
需要使用jdk自带的keytool来生成证书,如果已配置java环境变量,在任何目录启动命令行输入以下命令即可,若未配置java环境变量,则需要到jdk安装目录bin文件夹下启动命令行;
keytool -genkeypair -alias "testsys" -keyalg "RSA" -keystore "c:\test.keystore"
keytool -genkeypair -alias "tomcat" -keyalg "RSA" -keystore "D:\apache-tomcat-8.0.33\tomcat.keystore"
//其中-alias是证书的别名,RSA是加密算法,-keystore后是输出证书的路径所在
找到tomcat安装目录,在conf文件夹下找到server.xml,加入如下配置
<Connector port="9089" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile="E:\apache-tomcat-7.0.90\test.keystore" keystorePass="test123" connectionTimeout="20000" redirectPort="8443" useBodyEncodingForURI="true" URIEncoding="UTF-8"/>