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信任所有证书的更多相关文章

  1. java将SSL证书导入系统密钥库

    之前安装JIRA和Confluence,配置了SSL证书之后遇到应用程序链接的问题: SSL证书不被信任,导致JIRA和Confluence无法关联. 尝试过很多办法无果之后打算放弃. 最终还是放弃了 ...

  2. 【Java】Java与数字证书

    Java与数字证书 Java与数字证书 证书的签发和应用 证书的内容和意义 其它 证书(Certificate,也称public-key certificate)是用某种签名算法对某些内容(比如公钥) ...

  3. httpclient信任所有证书解决SSLException:Unrecognized SSL message,plaintext connection

    在使用 HttpClient 工具调用第三方 Http 接口时报错 javax.net.ssl.SSLException:Unrecognized SSL message,plaintext conn ...

  4. iOS开发HTTPS实现之信任SSL证书和自签名证书

    iOS开发HTTPS实现之信任SSL证书和自签名证书 转自:http://www.jianshu.com/p/6b9c8bd5005a/comments/5539345 (收录一下供自己学习用的) 字 ...

  5. IIS6的SSL配置,如何配置SSL到登陆页,如何将SSL证书设置成受信任的证书

    一. 申请证书1. 到受信任的机构申请 略 2. 到自建的证书服务器申请 a. 安装证书服务 通过控制面板中的“添加/删除程序”,选择“添加/删除Windows组件”.在Windows组件向导中找到“ ...

  6. JAVA中SSL证书认证通讯

    JAVA中SSL证书认证通讯 SSL通讯服务端 /******************************************************************** * 项目名称 ...

  7. dos批量导入不受信任的证书及软件限制策略的应用

    certmgr.exe -add "证书.cer" -s -r localMachine Disallowed 导入授信机构 certmgr -add "证书.cer&q ...

  8. iOS 中可用的受信任根证书列表

    iOS 中可用的受信任根证书列表 iOS 受信任证书存储区中包含随 iOS 一并预装的受信任根证书. 关于信任和证书 以下所列的各个 iOS 受信任证书存储区均包含三类证书: “可信”的证书用于建立信 ...

  9. iOS 9 中可用的受信任根证书列表

    iOS 受信任证书存储区包含随 iOS 预安装的可信根证书.  https://support.apple.com/zh-cn/HT205205 关于信任和证书 iOS 9 受信任证书存储区包含三类证 ...

随机推荐

  1. JS如何创建对象

    js创建对象的方法很多,以下分别介绍

  2. idea配置github

    一.事先准备 1.安装Git Git下载: http://git-scm.com/downloads 最新版本是2.1.2 git登陆地址:https://github.com/ 2.注册GitHub ...

  3. __cxa_call_unexpected原因

    coredump的调用栈: #0  0xf76f5440 in __kernel_vsyscall () #1  0xf73c4657 in raise () from /lib/libc.so.6 ...

  4. bzoj1212(trie+dp)

    开始一看多个字符串就想ac自动机,结果发现不行.果然学傻了,,,,只要建个trie然后刷表dp就行了,复杂度最坏是O(字典中最长单词长度*文章长度)的.trie的空间换时间挺不错的. #include ...

  5. webService之helloword(java)rs

    webservice之rs(helloworld) 1.pom.xml文件 <dependencies> <!-- 使用CXF RS开发 --> <dependency& ...

  6. 网络timeout区分

    ConnectTimeout 连接建立时间,三次握手完成时间 SocketTimeout 数据传输过程中数据包之间间隔的最大时间 下面重点说下SocketTimeout,比如有如下图所示的http请求 ...

  7. TypeScript开发环境搭建(Visual studio code)

    使用Visual Studio Code搭建TypeScript开发环境 1.TypeScript是干什么的 ? TypeScript是由微软Anders Hejlsberg(安德斯·海尔斯伯格,也是 ...

  8. STL其他--<tuple>用法【C11】

     tuple 库 tuple 库 是能够将不同类型的对象组合起来形成一个对象.和pair 对象一样,但是可以组织多种不同类型的元素. tuple中的元素类型是在编译时期决定的.与<utility ...

  9. MapReduce编程解析

    MapReduce编程模型之案例 wordcount 输入数据 atguigu atguiguss sscls clsjiaobanzhangxuehadoop 输出数据 atguigu 2banzh ...

  10. kafka_shell操作

    单机版 开启进程: ./bin/kafka-server-start.sh config/server.properties 查看topic列表: ./bin/kafka-topics.sh --li ...