java信任所有证书
package com.eeepay.cashOut.util; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; import javax.net.ssl.SSLContext; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import com.alibaba.fastjson.JSONObject; /**
*
* @author ws
*
*/
public class HttpClientUtil { private static final Log log = LogFactory.getLog(HttpClientUtil.class);
private static final String utf8 = "UTF-8"; private String requestEncoding;
private String responseEncoding;
private String requesParamstEncoding; public HttpClientUtil() {
super();
this.requestEncoding = utf8;
this.responseEncoding = utf8;
this.requesParamstEncoding = utf8;
} public HttpClientUtil(String requestEncoding, String responseEncoding, String requesParamstEncoding) {
super();
this.requestEncoding = requestEncoding;
this.responseEncoding = responseEncoding;
this.requesParamstEncoding = requesParamstEncoding;
}
public HttpClientUtil( String responseEncoding) {
super();
this.requestEncoding = utf8;
this.responseEncoding = responseEncoding;
this.requesParamstEncoding = utf8;
} public String getRequestEncoding() {
return requestEncoding;
} public void setRequestEncoding(String requestEncoding) {
this.requestEncoding = requestEncoding;
} public String getResponseEncoding() {
return responseEncoding;
} public void setResponseEncoding(String responseEncoding) {
this.responseEncoding = responseEncoding;
} public String getRequesParamstEncoding() {
return requesParamstEncoding;
} public void setRequesParamstEncoding(String requesParamstEncoding) {
this.requesParamstEncoding = requesParamstEncoding;
} /**
* 直接访问URL,可以自主设置是否以POST方式访问
* @param finalUrl URL
* @param post 访问方式,是否是Post访问
* @return
* @author Lumia_Zeng
* @date 2016年10月24日 上午10:00:11
*/
public Map<String, String> baseAccessURL(String finalUrl, boolean post) {
Map<String, String> map = new HashMap<String, String>();
String msg = "访问接口失败";
String exceptionMsg = null;
map.put("success", "false");
log.info("URL路径:" + finalUrl); RequestConfig config = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(40000).setConnectionRequestTimeout(40000).build();
Long startTime = System.currentTimeMillis();
CloseableHttpClient httpclient = createCloseableHttpClient(finalUrl,config);
HttpUriRequest httpMethod = null;
if(post){
HttpPost pMethod = new HttpPost(finalUrl);
pMethod.setConfig(config);
httpMethod = pMethod;
}else{
HttpGet gMethod = new HttpGet(finalUrl);
gMethod.setConfig(config);
httpMethod = gMethod;
} try {
HttpResponse resp = httpclient.execute(httpMethod);
Long endTime = System.currentTimeMillis();
log.info("耗时 "+(endTime-startTime) +" 毫秒");
Integer statusCode = resp.getStatusLine().getStatusCode();
String respContent = IOUtils.toString(resp.getEntity().getContent(), responseEncoding);
respContent = respContent==null ? "" : respContent;
map.put("success", "true");
msg = "访问接口成功";
map.put("responseBody", respContent);
map.put("responseStatusCode", statusCode.toString());
} catch (UnsupportedEncodingException e) {
exceptionMsg = "不支持的编码格式!";
e.printStackTrace();
} catch (ClientProtocolException e) {
exceptionMsg = "ClientProtocolException";
e.printStackTrace();
} catch (IOException e) {
exceptionMsg = "IOException";
e.printStackTrace();
} catch (IllegalStateException e) {
exceptionMsg = "IllegalStateException";
e.printStackTrace();
} catch (Exception e) {
exceptionMsg = "Exception";
e.printStackTrace();
}
map.put("msg", msg);
map.put("exceptionMsg", exceptionMsg);
return map;
} /**
* 以POST方式访问URL,参数以JSON形式传递
* @param finalUrl
* @param params
* @return
* @author Lumia_Zeng
* @date 2016年10月27日 下午4:07:49
*/
public Map<String, String> baseAccessURLJSON(String finalUrl,Map<String,String> params) {
return accessURL(finalUrl, params,true);
} /**
* 以POST方式访问URL
* @param finalUrl url
* @param params 参数
* @return
* @author Lumia_Zeng
* @date 2016年10月27日 下午4:07:02
*/
public Map<String, String> baseAccessURL(String finalUrl,Map<String,String> params) {
return accessURL(finalUrl, params,false);
} /**
* 访问URL,带参数
* @param finalUrl URL
* @param params 参数
* @param isJson 是否以JSON方式传递参数
* @return
* @author Lumia_Zeng
* @date 2016年10月24日 上午10:02:50
*/
public Map<String, String> accessURL(String finalUrl,Map<String,String> params,boolean isJson) {
Map<String, String> map = new HashMap<String, String>();
String msg = "访问接口失败";
String exceptionMsg = null;
map.put("success", "false"); log.info("baseAccessURL:" + finalUrl);
Long startTime = System.currentTimeMillis(); RequestConfig config = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(40000).setConnectionRequestTimeout(40000).build();
HttpClient httpclient;
httpclient= createCloseableHttpClient(finalUrl,config);
HttpUriRequest httpMethod = null;
HttpPost pMethod = new HttpPost(finalUrl);
pMethod.setConfig(config); try {
if(isJson && params!=null){
pMethod.addHeader("Content-Type", "application/json; charset=" + requestEncoding);
String strParams = JSONObject.toJSONString(params);
//log.info("JSON参数:" + strParams);
StringEntity entity = new StringEntity(strParams, requesParamstEncoding);
pMethod.setEntity(entity);
}else{
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
if(params != null){
Set<String> set = params.keySet();
for (String key : set) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
}
log.info("参数:" + nvps);
pMethod.setEntity(new UrlEncodedFormEntity(nvps, requesParamstEncoding));
} httpMethod = pMethod;
HttpResponse resp = httpclient.execute(httpMethod);
Integer statusCode = resp.getStatusLine().getStatusCode();
String respContent = IOUtils.toString(resp.getEntity().getContent(), responseEncoding);
respContent = respContent==null ? "" : respContent;
map.put("success", "true");
msg = "访问接口成功";
map.put("responseBody", respContent);
map.put("responseStatusCode", statusCode.toString());
} catch (ConnectTimeoutException e) {
exceptionMsg = "ConnectTimeoutException";
e.printStackTrace();
} catch (SocketTimeoutException e) {
exceptionMsg = "SocketTimeoutException";
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
exceptionMsg = "UnsupportedEncodingException";
e.printStackTrace();
} catch (ClientProtocolException e) {
exceptionMsg = "ClientProtocolException";
e.printStackTrace();
} catch (IOException e) {
exceptionMsg = "IOException";
e.printStackTrace();
} catch (IllegalStateException e) {
exceptionMsg = "IllegalStateException";
e.printStackTrace();
} catch (Exception e) {
exceptionMsg = "Exception";
e.printStackTrace();
} finally {
Long endTime = System.currentTimeMillis();
log.info("耗时 "+(endTime-startTime) +" 毫秒");
}
map.put("msg", msg);
map.put("exceptionMsg", exceptionMsg);
return map;
}
/***
* 传入JSON数据,以输出流的方式,发送请求
* @param urlStr 目标地址
* @param jsonStr JSON数据
* @param isPost 是否POST
* @return
* @author Lumia_Zeng
* @date 2016年11月1日 下午2:55:10
*/
public Map<String, String> accessURLByJsonStream(String urlStr, String jsonStr, boolean isPost) {
log.info(String.format("以JSON方式访问:%s;是否POST:%s;参数:%s",urlStr,isPost,jsonStr));
Map<String, String> map = new HashMap<String, String>();
String msg = "访问接口失败";
String exceptionMsg = null;
map.put("success", "false");
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
if (isPost) {
connection.setRequestMethod("POST");
}
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json; charset=" + requestEncoding);
connection.connect();
// POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(jsonStr.getBytes(requesParamstEncoding));
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder("");
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), responseEncoding);
sb.append(lines);
}
reader.close();
Integer statusCode = connection.getResponseCode();
// 断开连接
connection.disconnect();
map.put("success", "true");
msg = "访问接口成功";
map.put("responseBody", sb.toString());
map.put("responseStatusCode", statusCode.toString());
} catch (MalformedURLException e) {
exceptionMsg = e.getMessage();
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
exceptionMsg = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
exceptionMsg = e.getMessage();
e.printStackTrace();
} catch (Exception e) {
exceptionMsg = e.getMessage();
e.printStackTrace();
} finally {
map.put("msg", msg);
map.put("exceptionMsg", exceptionMsg);
}
return map;
} /**
*
* @param finalUrl
* @param config
* @return
*/
private CloseableHttpClient createCloseableHttpClient(String finalUrl,RequestConfig config){
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(config);
if (finalUrl.startsWith("https")) {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslsf);
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return builder.build();
} }
java信任所有证书的更多相关文章
- java将SSL证书导入系统密钥库
之前安装JIRA和Confluence,配置了SSL证书之后遇到应用程序链接的问题: SSL证书不被信任,导致JIRA和Confluence无法关联. 尝试过很多办法无果之后打算放弃. 最终还是放弃了 ...
- 【Java】Java与数字证书
Java与数字证书 Java与数字证书 证书的签发和应用 证书的内容和意义 其它 证书(Certificate,也称public-key certificate)是用某种签名算法对某些内容(比如公钥) ...
- httpclient信任所有证书解决SSLException:Unrecognized SSL message,plaintext connection
在使用 HttpClient 工具调用第三方 Http 接口时报错 javax.net.ssl.SSLException:Unrecognized SSL message,plaintext conn ...
- iOS开发HTTPS实现之信任SSL证书和自签名证书
iOS开发HTTPS实现之信任SSL证书和自签名证书 转自:http://www.jianshu.com/p/6b9c8bd5005a/comments/5539345 (收录一下供自己学习用的) 字 ...
- IIS6的SSL配置,如何配置SSL到登陆页,如何将SSL证书设置成受信任的证书
一. 申请证书1. 到受信任的机构申请 略 2. 到自建的证书服务器申请 a. 安装证书服务 通过控制面板中的“添加/删除程序”,选择“添加/删除Windows组件”.在Windows组件向导中找到“ ...
- JAVA中SSL证书认证通讯
JAVA中SSL证书认证通讯 SSL通讯服务端 /******************************************************************** * 项目名称 ...
- dos批量导入不受信任的证书及软件限制策略的应用
certmgr.exe -add "证书.cer" -s -r localMachine Disallowed 导入授信机构 certmgr -add "证书.cer&q ...
- iOS 中可用的受信任根证书列表
iOS 中可用的受信任根证书列表 iOS 受信任证书存储区中包含随 iOS 一并预装的受信任根证书. 关于信任和证书 以下所列的各个 iOS 受信任证书存储区均包含三类证书: “可信”的证书用于建立信 ...
- iOS 9 中可用的受信任根证书列表
iOS 受信任证书存储区包含随 iOS 预安装的可信根证书. https://support.apple.com/zh-cn/HT205205 关于信任和证书 iOS 9 受信任证书存储区包含三类证 ...
随机推荐
- 乌龙之Ignoring query to other database问题
问题现象: [root@zxdb05 ~]# mysql -root -pEnter password: Welcome to the MySQL monitor. Commands end wit ...
- day3用户交互,格式化输出,数据类型,流程控制
上节课复习: 1.运行python程序的三步骤:python test.py 1.先启动python解释器 2.将test.py的内容当作普通的字符读入内存 3.python解释器解释执行刚刚读入内存 ...
- 广搜 迷宫(zznu 1962)
http://acm.zznu.edu.cn/problem.php?id=1962 题目描述 在很多 RPG (Role-playing Games) 游戏中,迷宫往往是非常复杂的游戏环节.通常来说 ...
- hdu 1130 How Many Trees? 【卡特兰数】
题目 题意:给你一个数字n,问你将1~n这n个数字,可以组成多少棵不同的二叉搜索树. 1,2,5,14--根据输出中的规律可以看出这是一个卡特兰数的序列.于是代用卡特兰数中的一个递推式: 因为输入可取 ...
- 主题模型之概率潜在语义分析(Probabilistic Latent Semantic Analysis)
上一篇总结了潜在语义分析(Latent Semantic Analysis, LSA),LSA主要使用了线性代数中奇异值分解的方法,但是并没有严格的概率推导,由于文本文档的维度往往很高,如果在主题聚类 ...
- hdu 1059
题目大意:就是有价值1.2.3.4.5.6的硬币各多少个,然后让你判断能否把他们分成价值相等的两部分. 题目思路:目测dp,一看果然dp,完全背包,需要剪枝,硬币个数为容量,下标为value,用一个b ...
- hdu 4925 黑白格
http://acm.hdu.edu.cn/showproblem.php?pid=4925 给定一个N*M的网格,对于每个格子可以选择种树和施肥,默认一个苹果树收获1个苹果,在一个位置施肥的话,周围 ...
- floyd算法之最小环问题
最小环问题:都比较容易得到从u 到 v 经过中间某一些结点的最短路,但是我们得确保回来的时候,不能经过那些结点,这样我们就需要改一下floyd算法了 进而我们想到用Floyd算法.我们知道,Floyd ...
- 编程中常用的DOS命令
1. dir directory 无参数:查看当前所在目录的文件和文件夹. /s : 查看当前目录以及其所有子目录的文件和文件夹 /a :查看包含的隐含文件的所有文件. /ah :只显示出隐含文 ...
- 有人在用fastReport作报表时处理过字体自动缩小的问题吗,怎么做
有人在用fastReport作报表时处理过字体自动缩小的问题吗,怎么做 我来答 浏览 49 次 1个回答 #吃瓜大会# Angelababy演技被吐槽, 你觉得她的演技怎么样? 最佳答案 热心 ...