调用https请求,绕过证书校验;信任所有证书
https是http的增强版,使用了SSL/TLS证书验证;我们在请求https的过程中要在代码中设置证书的配置,以确保正常调用https。
需要引入httpclient相关jar包
httpclient-4.3.6.jar
httpclient-cache-4.3.6.jar
httpcore-4.3.3.jar
httpmime-4.3.6.jar
下面是设置与调用的代码样例:
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.ylink.gjj.isp.bots.core.bank.MonyGainBusloanRepay.util.CommonUtils;
import com.ylink.gjj.isp.bots.core.bank.MonyGainBusloanRepay.util.SM2Utils;
import com.ylink.gjj.isp.bots.core.bank.MonyGainBusloanRepay.util.SM4Util;
import com.ylink.sky.cache.helper.CacheHelper;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class HttpClientUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* 发送https请求共用体
*/
public static final String public_key = CacheHelper.getPropsValue("botsheader", "public_key");
public static final String private_key = CacheHelper.getPropsValue("botsheader", "private_key");
public static String sendHttpsPost(String reqPath, String postData) {
LOG.info("HttpClientUtil.sendHttpsPost url="+reqPath+"postData=" + postData);
HttpResponse response = null;
String result = "0";
HttpPost httpPost = null;
try {
String time = String.valueOf(System.currentTimeMillis());
String sm4KeyBak = private_key.concat(time);
String sm4Key = CommonUtils.hashString(sm4KeyBak);
String sm4Request = SM4Util.encodeText(postData, sm4Key);
String sign = SM2Utils.sign(sm4Request, private_key);
byte[] sm4RequestBytes = sm4Request.getBytes(StandardCharsets.UTF_8);
String charsetName = "utf-8";
HttpClient httpsClient = getHttpsClient();
httpPost = new HttpPost(reqPath);
httpPost.setHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json;charset=UTF-8");
httpPost.addHeader("bizKey", Base64.encode(public_key.getBytes()));
httpPost.addHeader("timestamp", time);
httpPost.addHeader("sign", sign);
httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
httpPost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
LOG.info("HttpClientUtil.sendHttpsPost bizKey:"+Base64.encode(public_key.getBytes())+"; timestamp:"+time+"; sign"+sign+"; sm4Request"+sm4Request);
//设定请求连接超时相关
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setSocketTimeout(60 * 1000).setConnectTimeout(10000).build();
httpPost.setConfig(requestConfig);
//添加参数
httpPost.setEntity(new StringEntity(sm4Request, Charset.forName(charsetName)));
response = httpsClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), charsetName);
LOG.info("请求返回结果:"+ result);
if( result == null ||"".equals(result)){
result = "0";
}
// 关闭连接
} catch (Exception e) {
LOG.error("接口地址:"+reqPath + " ,IOException,异常原因: "+ e.getMessage());
LOG.error(e.getMessage());
}finally {
try {
if (response != null) {
HttpClientUtils.closeQuietly(response);
}
if (httpPost != null) {
httpPost.releaseConnection();
}
}catch (Exception e){
LOG.error("httpPostReq关闭流异常,异常原因:"+e.toString());
}
}
return result;
}
public static HttpClient getHttpsClient() {
HttpClient httpClient = null;
SSLContext context;
try {
context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] {new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
X509HostnameVerifier verifier = new X509HostnameVerifier() {
@Override
public void verify(String s, SSLSocket sslSocket) throws IOException {
}
@Override
public void verify(String s, X509Certificate x509Certificate) throws SSLException {
}
@Override
public void verify(String s, String[] strings, String[] strings1) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return false;
}
};
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(context,verifier);
httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
} catch (Exception e) {
LOG.error(e.getMessage());
}
return httpClient;
}
}