解决Java调用Azure SDK证书错误javax.net.ssl.SSLHandshakeException
工具类:
package com.muxin.util;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
*/
public class HttpTookit {
private static Logger logger = LoggerFactory.getLogger(HttpTookit.class);
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(300000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map<String, Object> params){
if(isHttps(url)){
return sendSSLPostMethod(url, params);
}
else{
return doGet(url, params,CHARSET);
}
}
public static String doPost(String url, Map<String, Object> params){
return doPost(url, params,CHARSET);
}
/**
* HTTP Get 获取内容
* @param url 请求的url地址 ?之前的地�?
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url, Map<String, Object> params, String charset){
if(StringUtils.isBlank(url)){
return null;
}
HttpGet httpGet = null;
try {
if(params != null && !params.isEmpty()){
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for(Entry<String, Object> entry : params.entrySet()){
if(entry.getValue() != null){
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
logger.info("=======HttpTookit 请求url地址: "+url+"==========");
httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("httpclient请求失败");
}finally{
if(httpGet != null) httpGet.releaseConnection();
}
}
/**
* HTTP Post 获取内容
* @param url 请求的url地址 ?之前的地�?
* @param params 请求的参�?
* @param charset 编码格式
* @return 页面内容
*/
public static String doPost(String url, Map<String, Object> params, String charset){
if(StringUtils.isBlank(url)){
return null;
}
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
List<NameValuePair> pairs = null;
if(params != null && !params.isEmpty()){
pairs = new ArrayList<NameValuePair>(params.size());
for(Entry<String, Object> entry : params.entrySet()){
if(entry.getValue() != null){
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
}
}
httpPost = new HttpPost(url);
httpPost.setHeader("serialSeq","1212121");
httpPost.setHeader("verChl","0.0.1");
httpPost.setHeader("sendChl","hzsmk.test");
httpPost.setHeader("sendClient","hellohzsmk");
httpPost.setHeader("sendDev","121aqweq");
if(pairs != null && pairs.size() > 0){
httpPost.setEntity(new UrlEncodedFormEntity(pairs,CHARSET));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("httpclient请求失败");
} finally{
if(httpPost != null) httpPost.releaseConnection();
}
}
/**
* 初始化http请求参数
*
* @param url
* @param method
* @return
* @throws Exception
*/
protected static HttpsURLConnection initHttps(String url, String method,
Map<String, String> headers) throws Exception {
TrustManager[] tm = {new MyX509TrustManager()};
System.setProperty("https.protocols", "TLSv1");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
//sslContext.init(null, tm, null);
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
// 设置域名校验
http.setHostnameVerifier(new TrustAnyHostnameVerifier());
// 连接超时
http.setConnectTimeout(DEF_CONN_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(DEF_READ_TIMEOUT);
http.setUseCaches(false);
http.setRequestMethod(method);
/* http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");*/
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
try {
http.connect();
} catch (Exception ex) {
logger.info(ex.getMessage());
}
return http;
}
/**
* 功能描述: 构造请求参数
*
* @return 返回类型:
* @throws Exception
*/
public static String initParams(String url, Map<String, Object> params)
throws Exception {
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
}
sb.append(map2Url(params));
return sb.toString();
}
/**
* map构造url
*
* @return 返回类型:
* @throws Exception
*/
public static String map2Url(Map<String, Object> paramToMap)
throws Exception {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Entry<String, Object> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue().toString();
if (!StringUtils.isEmpty(value)) {
url.append(URLEncoder.encode(value, CHARSET));
}
}
return url.toString();
}
/**
* 检测是否https
*
* @param url
*/
protected static boolean isHttps(String url) {
return url.startsWith("https");
}
/**
* https 域名校验
*
* @return
*/
public static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;// 直接返回true
}
}
public static class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
/**
* 忽视证书HostName
*/
private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslsession) {
System.out.println("WARNING: Hostname is not matched for cert.");
return true;
}
};
/**
* Ignore Certification
*/
private static TrustManager ignoreCertificationTrustManger = new X509TrustManager(){
private X509Certificate[] certificates;
public void checkClientTrusted(X509Certificate certificates[],
String authType) throws CertificateException {
if (this.certificates == null) {
this.certificates = certificates;
}
}
public void checkServerTrusted(X509Certificate[] ax509certificate,
String s) throws CertificateException {
if (this.certificates == null) {
this.certificates = ax509certificate;
}
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
public static String sendSSLGetMethod(String urlString) throws Exception {
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
connection = (HttpsURLConnection) url.openConnection();
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
is.close();
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
public static byte[] sendSSLGetMethodByte(String urlString) throws Exception {
byte[] repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
ByteArrayOutputStream os = null;
byte[] buff = new byte[1024];
int len = 0;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
connection = (HttpsURLConnection) url.openConnection();
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
os = new ByteArrayOutputStream();
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len);
}
return os.toByteArray();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
is.close();
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
public static String sendSSLPostMethod(String urlString, String postData) throws Exception {
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type","text/json");
connection.setRequestProperty("content-length", String.valueOf(postData.getBytes().length));
connection.getOutputStream().write(postData.getBytes("utf-8"));
connection.getOutputStream().flush();
connection.getOutputStream().close();
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
is.close();
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
public static String sendSSLPostMethod(String urlString, Map<String, Object> params){
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(initParams(urlString,params));
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type","text/json");
//connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
//connection.getOutputStream().write(postData.getBytes("utf-8"));
connection.getOutputStream().flush();
connection.getOutputStream().close();
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
}
调用案例:
get请求:
String url ="";
String uResult = null;
try {
uResult = HttpTookit.sendSSLGetMethod(url);
} catch (Exception e) {
e.printStackTrace();
}
post请求:
String url ="";
String uResult = null;
try {
uResult = HttpTookit.sendSSLPostMethod(url);
} catch (Exception e) {
e.printStackTrace();
}
下载文件转byte[](以下载图片为例):
String downLoadUrl="";
byte[] s = HttpTookit.sendSSLGetMethodByte(downLoadUrl);