java httpclient跳過https證書驗證

感謝   java httpclient跳過https證書驗證 - 九條尾巴的貓 - 博客園 (cnblogs.com)

package com.cck.common.Utils;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class SkipHttpsUtil {

//繞過證書
public static HttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
ctx, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(ssf).build();
return httpclient;
} catch (Exception e) {
return HttpClients.createDefault();
}
}



}










public  String sendHttpPost(String url, String regJson) throws Exception {
SkipHttpsUtil skipHttpsUtil=new SkipHttpsUtil();

CloseableHttpClient httpClient =(CloseableHttpClient)skipHttpsUtil.wrapClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(regJson,"UTF-8")); //防止中文亂碼

CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
return responseContent;
}













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章