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. web程序打包详解

       重要更新:鉴于很多小伙伴们说看不到图,我这边换了几个浏览器看了下,都看得到的,估计是网速问题,请耐心等待,另外,为了更好的方便大家学习,特此提供源码以及一个word文档,word文档就是本文内容 ...

  2. HDU 1404 Digital Deletions (暴力博弈)

    题意:给定一个数字串,最长是6,然后有两种操作. 第一种是,把该串中的一个数字换成一个比该数字小的数,比如 5 可以换成 0,1,2,3,4.   e.g. 12345 --> 12341 第二 ...

  3. java并发里的一些基础概念

    转载自:https://my.oschina.net/hosee/blog/597934: 摘要: 本系列基于炼数成金课程,为了更好的学习,做了系列的记录. 本文主要介绍 1.高并发的概念,为以后系列 ...

  4. Switch 选择结构

    switch 选择器 一.语法 switch(变量名){ case 情况1: //代码块 break: case 情况1: //代码块 break: default(默认): //代码块 break: ...

  5. javascript的Mixins

    mixin在javascript里可以看作是一种从别的对象"借用"功能的方法.每一个新定义的对象都有一个 prototype属性,其他的对象就可以从这里"借用" ...

  6. 终端简单使用 &vim编写代码

    vim简单实用 & 用vim编写代码 ##  简单介绍  ## vi 1.c 建立1.c(文件存在,则打开1.c) vi共有三种模式: 按esc进入指令模式 按i进入编辑模式(按i光标位置不变 ...

  7. redis简单使用

    主要参考资料:http://wiki.jikexueyuan.com/project/redis-guide/data-type.html一.redis 安装1.在官网下载安装包2.解压安装包 tar ...

  8. Nutch1.2 的安装与使用

    Nutch1.2的安装与使用 1.nutch1.2下载    下载地址 http://archive.apache.org/dist/nutch/     2.nutch1.2目录   bin:用于命 ...

  9. 用命令行上传本地代码到GitHub

    有两种方式上传,ssh和https,ssh老是报错=.=我用的是https 先下载git   https://git-scm.com/downloads 在代码的文件夹的同级目录中邮件打开git ba ...

  10. Git 安装 windows && linux

    一.安装: windows下安装Git: 1.下载Git:https://git-scm.com/download/win 2.安装Git:默认安装,一直回车 Linux下安装Git: yum安装: ...