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. python:OS模块

    r"""OS routines for NT or Posix depending on what system we're on. This exports: - al ...

  2. *单链表[递归&不带头结点]

    不带头结点的单链表,递归法比较简明!(必背!) 单链表的结构: typedef struct node{ int data; struct node *next; }*List,Node; 创建第一种 ...

  3. 1045 Favorite Color Stripe 动态规划

    1045 Favorite Color Stripe 1045. Favorite Color Stripe (30)Eva is trying to make her own color strip ...

  4. 20171123IdleHandler

    在Android中,我们可以处理Message,这个Message我们可以立即执行也可以delay 一定时间执行.Handler线程在执行完所有的Message消息,它会wait,进行阻塞,知道有心的 ...

  5. text 文本。

    //支持转义符"\".   <text/> 组件内只支持 <text/> 嵌套. //除了文本节点以外的其他节点都无法长按选中. <view clas ...

  6. 20145232 韩文浩 《Java程序设计》第3周学习总结

    教材学习内容总结 在第三章中,知道了Java可区分为基本类型和类类型两大类型系统,其中类类型也称为参考类型.在这一周主要学习了类类型. 对象(Object):存在的具体实体,具有明确的状态和行为 类( ...

  7. hdu 4968 最大最小gpa

    http://acm.hdu.edu.cn/showproblem.php?pid=4968 给定平均分和科目数量,要求保证及格的前提下,求平均绩点的最大值和最小值. dp[i][j]表示i个科目,总 ...

  8. centos7 修改默认启动级别

    systemctl set-default multi-user.target      设定默认为字符界面,也就是3 systemctl set-default graphical.target  ...

  9. Android-HttpClient-Get与Post请求登录功能

    HttpClient 是org.apache.http.* 包中的: 第一种方式使用httpclient-*.jar (需要在网上去下载httpclient-*.jar包) 把httpclient-4 ...

  10. 【xcode中添加pch全局引用文件】

    前沿:xcode6中去掉了pch,为了一些琐碎的头文件引用,加快了 编译速度! xcode6之前的版本建项目就自动添加了是这样的: xcode6后的版本要自己手动的添加步骤如下: 1)  2) 3)  ...