报错显示:
javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
用下边这篇文章,成功解决。工具类:
/*
* Log changed by Date Desc
* L48972_1 huang.hui 2018-12-18 调用接口,绕开验证
*/
package com.css.eshop.util;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
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.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.css.eshop.model.Respones;
import com.css.eshop.model.TokenVo;
import com.google.gson.Gson;
public class HttpClientNoValidation {
protected static Log logger = LogFactory.getLog(HttpClientUtil.class);
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
/**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendPost(String url, Map map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
List nvps = new ArrayList();
if(map!=null){
for (Entry entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
/**
* 模拟请求Get
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static Respones send(String url, Map map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String body = "";
String strResult = "";
Respones responseVo = new Respones();
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response=null;
try {
//创建post方式请求对象
//HttpPost httpPost = new HttpPost(url);
HttpGet httpget= new HttpGet(url);
//装填参数
List nvps = new ArrayList();
if(map!=null){
for (Entry entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
//httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpget.setHeader("Content-type", "application/x-www-form-urlencoded");
httpget.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
response = client.execute(httpget);
//获取结果实体
HttpEntity entity = response.getEntity();
int iGetResultCode = response.getStatusLine().getStatusCode();
if (entity != null) {
//按指定编码转换结果实体为String类型
//body = EntityUtils.toString(entity, encoding);
strResult = EntityUtils.toString(entity);
}
responseVo.setResponeCde(iGetResultCode);
responseVo.setResult(strResult);
//EntityUtils.consume(entity);
} catch (Exception ex) {
responseVo.setResponeCde(500);
responseVo.setResult("error");
logger.error("executeGetMethod", ex);
} finally {
try {
if(response !=null){
response.close();
}
} catch (Exception e) {
logger.error("executeGetMethod", e);
}
}
//释放链接
response.close();
return responseVo;
}
/**
* 模拟请求Get()
*
* @param url 资源地址
* @param map 参数列表
* @param map token
* @param encoding 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static Respones sendTokenToGet(String url, Map map,Respones tokenRespones,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
//处理token参数 start
String token = tokenRespones.getResult();
if(tokenRespones.getResponeCde() >= 303){
return tokenRespones;
}
Gson gson = new Gson();
TokenVo t = gson.fromJson(token, TokenVo.class);
logger.info(" Token\t: " + t.getToken());
token = t.getToken();
//处理token参数 end
String body = "";
String strResult = "";
Respones responseVo = new Respones();
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response=null;
try {
//创建post方式请求对象
//HttpPost httpPost = new HttpPost(url);
HttpGet httpget= new HttpGet(url);
//装填参数
List nvps = new ArrayList();
if(map!=null){
for (Entry entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
//httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpget.setHeader("Content-type", "application/x-www-form-urlencoded");
httpget.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpget.setHeader("Authorization", token);
//执行请求操作,并拿到结果(同步阻塞)
response = client.execute(httpget);
//获取结果实体
HttpEntity entity = response.getEntity();
int iGetResultCode = response.getStatusLine().getStatusCode();
if (entity != null) {
//按指定编码转换结果实体为String类型
//body = EntityUtils.toString(entity, encoding);
strResult = EntityUtils.toString(entity);
}
responseVo.setResponeCde(iGetResultCode);
responseVo.setResult(strResult);
//EntityUtils.consume(entity);
} catch (Exception ex) {
responseVo.setResponeCde(500);
responseVo.setResult("error");
logger.error("executeGetMethod", ex);
} finally {
try {
if(response !=null){
response.close();
}
} catch (Exception e) {
logger.error("executeGetMethod", e);
}
}
//释放链接
response.close();
return responseVo;
}
public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException {
//获取token
String url = "https://..../token";//获取token的地址
Respones body = send(url, null, "utf-8");
System.out.println("交易响应结果:");
System.out.println(body.getResponeCde());
System.out.println(body.getResult());
//使用get调用接口,并传token
String url2="https://....";
Respones body2 = sendTokenToGet(url2, null,body, "utf-8");
System.out.println(body2.getResponeCde()+", "+body2.getResult());
System.out.println("-----------------------------------");
}
实体类:
import java.io.Serializable;
public class Respones implements Serializable{
private static final long serialVersionUID = 1L;
private int responeCde;
private String result;
public int getResponeCde() {
return responeCde;
}
public void setResponeCde(int responeCde) {
this.responeCde = responeCde;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
package com.css.eshop.model;
public class TokenVo {
private String ip;
private String token;
private String expiration;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getExpiration() {
return expiration;
}
public void setExpiration(String expiration) {
this.expiration = expiration;
}
}
在python中,requests.get(url,verify=False) 设置一下就ok。
httpclient不能直接访问https的资源,这次就来模拟一下环境,然后配置https测试一下。在前面的文章中,分享了一篇自己生成并在tomcat中配置ssl的文章《Tomcat配置SSL》,大家可以据此来在本地配置https。我已经配置好了,效果是这样滴:
可以看到已经信任该证书(显示浅绿色小锁),浏览器可以正常访问。现在我们用代码测试一下:
public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException, HttpProcessException {
String url = "https://sso.tgb.com:8443/cas/login";
String body = send(url, null, "utf-8");
System.out.println("交易响应结果:");
System.out.println(body);
System.out.println("-----------------------------------");
}
发现抛出了异常,我知道的有两种方案(也许还有我不知道的方案),这里介绍第一种方案,也是用的比较多的方案——绕过证书验证。直接看代码吧:
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
然后修改原来的send方法:
/**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static String send(String url, Map map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
List nvps = new ArrayList();
if(map!=null){
for (Entry entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
现在再进行测试,发现果然通了。
---------------------
原文:https://blog.csdn.net/xiaoxian8023/article/details/49865335
参考博客:
https://blog.csdn.net/xiaoxian8023/article/category/5968067