httpclient访问部分网站https不正常,证书是DigiCert SHA2 Secure Server CA
报错
unable to find valid certification path to requested target
Prime size must be multiple of 64, and can only range from 512 to 1024
解决方案:
import java.security.Security;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
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;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;public class HttpsUtil {
/**
* 此实例只可创建一个,否则会有内存泄露
*/
public static final BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();static {
Security.addProvider(bouncyCastleProvider);
}
/**
* 发送https请求,忽略证书
* @param url
* @param httpMethod HttpGet/HttpPost/...
* @return 返回接口报文
*/
public static String sendHttpsRequestIgnoreCertify(String url, HttpRequestBase httpMethod) {
SSLContext sslcontext;
try {
sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
return true;
}
}).build();
} catch (Exception e) {
throw new RuntimeException("HTTPS接口构建失败", e);
}SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null,
new NoopHostnameVerifier());CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSf).build();
HttpResponse res = null;
int statusCode = 0;
String respStr = null;
try {
res = client.execute(httpMethod);
statusCode = res.getStatusLine().getStatusCode();
HttpEntity entity = res.getEntity();
respStr = EntityUtils.toString(res.getEntity(), "utf-8");// 返回json格式:
} catch (Exception e) {
throw new RuntimeException("HTTPS接口"+url+"请求失败,失败信息:" + e.getMessage(), e);
} finally {
httpMethod.releaseConnection();
}
return respStr;
}public static void main(String[] args) {
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000*5).setSocketTimeout(1000*30).build();
String url = "https://xx.xx.xx/";
HttpGet get = new HttpGet(url);
get.setConfig(config);
String respStr = sendHttpsRequestIgnoreCertify(url, get);
System.out.println(respStr);
System.out.println("------");
HttpPost post = new HttpPost(url);
post.setConfig(config);
String respStr2 = sendHttpsRequestIgnoreCertify(url, post);
System.out.println(respStr2);
}
}