Linux下tomcat配置ssl中报错问题的解决javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateExcepti

原问题:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

http://blog.csdn.net/robert_lizhiqiang/article/details/44060217

解决报错问题:>

static {
	    //for localhost testing only 
	    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
	    new javax.net.ssl.HostnameVerifier(){
 
	        public boolean verify(String hostname,
	                javax.net.ssl.SSLSession sslSession) {
	            if (hostname.equals("localhost")) {
	                return true;
	            }else  if (hostname.equals("118.85.194.45")) {
	                return true;
				}
	            return false;
	        }
	    });
	}


http://www.mkyong.com/webservices/jax-ws/java-security-cert-certificateexception-no-name-matching-localhost-found/

或者[建议上边的]

http://stackoverflow.com/questions/19540289/how-to-fix-the-java-security-cert-certificateexception-no-subject-alternative

解决连接https问题

public static String requestHTTPS(String targetUrl, String method, Map params) {
		try {
			log.debug("requestHTTPS targetUrl:"+targetUrl+",method:"+method);
			System.out.println(targetUrl);
			URL url = new URL(targetUrl);
			HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection) url
					.openConnection();
			/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
			//http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection
			//javax.net.ssl.SSLSocketFactory
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			FileInputStream instream = new FileInputStream(new File("/Users/yol/Documents/id.keystore"));
			try {
				// 加载keyStore   
				trustStore.load(instream, "D#s@a1".toCharArray());
			} catch (CertificateException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} finally {
				try {
					instream.close();
				} catch (Exception ignore) {
				}
			}
			TrustManagerFactory tmf = 
					  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			tmf.init(trustStore);
			
			//
			X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];

			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(null, new TrustManager[] {defaultTrustManager}, null);
			
			SSLSocketFactory sslFactory = ctx.getSocketFactory();
			
			connection.setSSLSocketFactory(sslFactory);

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("Accept", "application/json");
			
			connection.connect();
			if(params!=null){
				//POST请求
				DataOutputStream out = new DataOutputStream(
						connection.getOutputStream());
				out.writeBytes(buildRequestParams(params,"UTF-8"));
				out.flush();
				out.close();
			}
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			connection.disconnect();
			log.debug("response:"+sb.toString());
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KeyStoreException e1) {
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return null;
	}


http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection

细节修定:

http://kerbtier.ch/2009/01/31/urlconnection-and-https

注意中间
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];

的细节问题

全部代码如下:

package com.upyoo.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UtilRest {
	private static Log log=LogFactory.getLog(UtilRest.class);
	static {
	    //for localhost testing only 
	    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
	    new javax.net.ssl.HostnameVerifier(){
 
	        public boolean verify(String hostname,
	                javax.net.ssl.SSLSession sslSession) {
	            if (hostname.equals("localhost")) {
	                return true;
	            }else  if (hostname.equals("118.85.194.45")) {
	                return true;
				}
	            return false;
	        }
	    });
	}
	
	public static void main(String[] args) {
    	JSONObject response=UtilRest.post("https://118.85.194.45:8080/");
	}
	public static JSONObject get(String targetUrl) {
		HttpClient httpClient = new HttpClient();

		HttpMethodBase method = new GetMethod();
		JSONObject response = null;
		try {
			method.setURI(new URI(targetUrl, false));
			int statusCode = httpClient.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				System.out.println("Method failed: "
						+ method.getStatusLine() + " for url " + targetUrl);
			}
			String strResponse = method.getResponseBodyAsString();
			response = JSONObject.fromObject(strResponse);
			return response;
		} catch (Exception e) {
			log.error("Please check your provided http address!");
		} finally {
			if (method != null)
				method.releaseConnection();
		}
		if (response == null)
			return null;
		return null;
	}
	public static JSONObject post(String targetUrl) {
		return post(targetUrl,null);
	}
	public static JSONObject post(String targetUrl,Map params) {
		String result = null;
		if (targetUrl.startsWith("https")) {
			result = requestHTTPS(targetUrl, "POST",params);
			
		}else if (targetUrl.startsWith("http")) {
			result = request(targetUrl, "POST",params);

		}
		if (result != null)
			try {
				return JSONObject.fromObject(result);
			} catch (Exception e) {
			}
		return null;
	}
	public static JSONObject put(String targetUrl) {
		String result = request(targetUrl, "PUT",null);
		if (result != null)
			try {
				return JSONObject.fromObject(result);
			} catch (Exception e) {
			}
		return null;
	}
	public static JSONObject delete(String targetUrl) {
		String result = request(targetUrl, "DELETE",null);
		if (result != null)
			try {
				return JSONObject.fromObject(result);
			} catch (Exception e) {
			}
		return null;
	}

	public static String request(String targetUrl, String method, Map params) {
		try {
			log.debug("request targetUrl:"+targetUrl+",method:"+method);
			URL url = new URL(targetUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("Accept", "application/json");

			connection.connect();
			if(params!=null){
	            //POST请求
	            DataOutputStream out = new DataOutputStream(
	                    connection.getOutputStream());
	            out.writeBytes(buildRequestParams(params,"UTF-8"));
	            out.flush();
	            out.close();
            }

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			connection.disconnect();
			log.debug("response:"+sb.toString());
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static String requestHTTPS(String targetUrl, String method, Map params) {
		try {
			log.debug("requestHTTPS targetUrl:"+targetUrl+",method:"+method);
			System.out.println(targetUrl);
			URL url = new URL(targetUrl);
			HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection) url
					.openConnection();
			/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
			//http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection
			//javax.net.ssl.SSLSocketFactory
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			FileInputStream instream = new FileInputStream(new File("/Users/yol/Documents/id.keystore"));
			try {
				// 加载keyStore   
				trustStore.load(instream, "D#s@a1".toCharArray());
			} catch (CertificateException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} finally {
				try {
					instream.close();
				} catch (Exception ignore) {
				}
			}
			TrustManagerFactory tmf = 
					  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			tmf.init(trustStore);
			
			//
			X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];

			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(null, new TrustManager[] {defaultTrustManager}, null);
			
			SSLSocketFactory sslFactory = ctx.getSocketFactory();
			
			connection.setSSLSocketFactory(sslFactory);

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("Accept", "application/json");
			
			connection.connect();
			if(params!=null){
				//POST请求
				DataOutputStream out = new DataOutputStream(
						connection.getOutputStream());
				out.writeBytes(buildRequestParams(params,"UTF-8"));
				out.flush();
				out.close();
			}
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			connection.disconnect();
			log.debug("response:"+sb.toString());
			return sb.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KeyStoreException e1) {
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String buildRequestParams(Map params,
            String charset) throws UnsupportedEncodingException {
        if (params == null || params.isEmpty()) {
            return null;
        }
         
        // 对参数进行排序
        List> newParams = new ArrayList>(
                params.entrySet());
        Collections.sort(newParams,
                new Comparator>() {
                    public int compare(Map.Entry o1,
                            Map.Entry o2) {
                        return (o1.getKey()).toString().compareTo(o2.getKey());
                    }
                });
 
        StringBuilder query = new StringBuilder();
        for (Map.Entry entry : newParams) {
            String name = entry.getKey();
            String value = entry.getValue();
            query.append("&");
            query.append(name).append("=").append(URLEncoder.encode(value, charset));
        }
        if(!"".equalsIgnoreCase(query.toString()))
        	return query.toString().substring(1, query.toString().length());
        return query.toString();
    }
}


使用httpclient组件的方式:

package com.paymoon.demo.httpClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class HttpClientTest {

	public static void main(String[] args) {
		HttpClientTest client = new HttpClientTest();
		client.ssl();
	}

	/**
	 * HttpClient连接SSL
	 */
	public void ssl() {
		CloseableHttpClient httpclient = null;
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			FileInputStream instream = new FileInputStream(new File("/Users/yol/Documents/id.keystore"));
			try {
				// 加载keyStore d:\\tomcat.keystore  
				trustStore.load(instream, "D#s@a1".toCharArray());
			} catch (CertificateException e) {
				e.printStackTrace();
			} finally {
				try {
					instream.close();
				} catch (Exception ignore) {
				}
			}
			// 相信自己的CA和所有自签名的证书
			SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
			// 只允许使用TLSv1协议
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
					SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			// 创建http请求(get方式)
			HttpPost httpget = new HttpPost("https://118.85.194.45:8080");
			System.out.println("executing request" + httpget.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				if (entity != null) {
					System.out.println("Response content length: " + entity.getContentLength());
					System.out.println(EntityUtils.toString(entity));
					EntityUtils.consume(entity);
				}
			} finally {
				response.close();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * post方式提交表单(模拟用户登录请求)
	 */
	public void postForm() {
		// 创建默认的httpClient实例.  
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost  
		HttpPost httppost = new HttpPost("https://118.85.194.45:9001/ucid/app/login");
		// 创建参数队列  
		List formparams = new ArrayList();
		formparams.add(new BasicNameValuePair("user", "monitor"));
		formparams.add(new BasicNameValuePair("password", "123456"));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("--------------------------------------");
					System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
					System.out.println("--------------------------------------");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源  
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
	 */
	public void post() {
		// 创建默认的httpClient实例.  
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost  
		HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
		// 创建参数队列  
		List formparams = new ArrayList();
		formparams.add(new BasicNameValuePair("type", "house"));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			System.out.println("executing request " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("--------------------------------------");
					System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
					System.out.println("--------------------------------------");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源  
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送 get请求
	 */
	public void get() {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.  
			HttpGet httpget = new HttpGet("https://118.85.194.45:8080");
			System.out.println("executing request " + httpget.getURI());
			// 执行get请求.  
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体  
				HttpEntity entity = response.getEntity();
				System.out.println("--------------------------------------");
				// 打印响应状态  
				System.out.println(response.getStatusLine());
				if (entity != null) {
					// 打印响应内容长度  
					System.out.println("Response content length: " + entity.getContentLength());
					// 打印响应内容  
					System.out.println("Response content: " + EntityUtils.toString(entity));
				}
				System.out.println("------------------------------------");
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源  
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 上传文件
	 */
	public void upload() {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");

			FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
			StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

			HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();

			httppost.setEntity(reqEntity);

			System.out.println("executing request " + httppost.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					System.out.println("Response content length: " + resEntity.getContentLength());
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
//



你可能感兴趣的:(Linux下tomcat配置ssl中报错问题的解决javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateExcepti)