实现思路
1、重写证书信任管理器(javax.net.ssl.X509TrustManager)
2、构建 套接字会话工厂
3、Apache封装ssl连接工程
4、构建Http客户端
5、客户端设置访问连接和参数
6、触发访问
依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
源码
package com.zhicheng.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
/**
* 1、非加密https
* 2、忽略服务端正式的合法性
* @author wb-zcf274530
*
*/
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
private static final String[] IMAGE_CONTENT_TYPE = {"","","",""};
/**
* TODO 总觉得异常时返回默认是不妥的,模式具有二义性
* @return
*/
private static CloseableHttpClient createSSLClientDefault(){
//重写是否对服务端证书进行校验
X509TrustManager x509mgr = new X509TrustManager() {
//检查客户端证书,若不信任该证书则抛出异常
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
//检查服务端证书,如不信任该证书则抛出异常
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
//返回受信任的X509证书
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
//实例化安全套接字工厂
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
//用自定义的证书管理器初始化
sslContext.init(null, new TrustManager[] { x509mgr }, null);
//构建套接字连接工厂
SSLConnectionSocketFactory sslsf =
new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
//使用自定义的证书管理器连接工厂创建http客户端
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException |NoSuchAlgorithmException e) {
logger.error("create SSLClient with custom TrustManager fail",e);
}
//创建默认HTTP客户端
/**
* maybe,this branch should not exist.
* it make the method two sense!
*/
return HttpClients.createDefault();
}
public static String sendSSLPostRequestWithoutVerify02(String reqURL, Map<String, String> params) throws ClientProtocolException, IOException {
String responseStr = "";
HttpClient httpClient = createSSLClientDefault();
//构造一个post请求
HttpPost httpPost = new HttpPost(reqURL);
//设置请求参数
List<NameValuePair> formParams = new ArrayList();
Iterator var11 = params.entrySet().iterator();
while(var11.hasNext()) {
Entry<String, String> entry = (Entry)var11.next();
formParams.add(new BasicNameValuePair((String)entry.getKey(), (String)entry.getValue()));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
} catch (UnsupportedEncodingException e) {
//will no happen!
}
try {
//Dose the reposne has a statusCode?
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(null!=entity) {
//ContentType.getOrDefault(entity); 返回content-type
responseStr = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
}
} finally {
try {
if(httpClient!=null) {
((CloseableHttpClient)httpClient).close();
}
} catch (IOException e) {
//ignore
};
}
return responseStr;
}
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, IOException {
String imageUrl = "https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=https%3A%2F%2Ftimgsa.baidu.com%2Ftimg%3Fimage%26quality%3D80%26size%3Db10000_10000%26sec%3D1525397679%26di%3D5d7896865aa65ab36eb1759843a6a22b%26src%3Dhttp%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201411%2F13%2F20141113131626_QUA2n.png";
String strUrl = "https://blog.csdn.net/jeanflower/article/details/74494136";
Map<String,String> params = new HashMap<String,String>();
//params.put("resourceId", "daec345f-d90b-4fd7-948d-930faa423e44");
//params.put("resourceName", "123.docx");
//params.put("ossServiceCode", "antis_contract_default_oss");
String reponseStr = sendSSLPostRequestWithoutVerify02(imageUrl,params);
logger.debug(reponseStr);
/*X509TrustManager x509mgr = new X509TrustManager() {
//
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
//
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
//
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, new X509TrustManager[]{x509mgr}, new java.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL("https://www.baidu.com/");
//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection();
httpsConn.setSSLSocketFactory(ssf);
System.out.println(JSONObject.toJSONString(httpsConn.getContent()));*/
}
}
}
}