package com.iups.wx.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
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 net.sf.json.JSONObject; import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.entity.StringEntity;
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.util.EntityUtils;
import org.apache.log4j.Logger; /**
* 调用远程接口工具类
* @author Administrator
* @date 2017年2月16日 13:44:03
*/
public class HttpsClientUtil { //日志
public static Logger log = Logger.getLogger(HttpsClientUtil.class);
//编码方式
private static String UTF8 = "UTF-8";
//数据格式
private final String APPLICATION_JSON = "application/json";
//数据类型标识
public final String CONTENT_TYPE = "Content-Type";
//https请求客户端
private CloseableHttpClient httpclient = null; private static HttpsClientUtil httpsClientUtil; private HttpsClientUtil(){
try{
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{
//证书信任管理器(用于https请求)
new X509TrustManager(){
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}, new SecureRandom());
//获取注册建造者
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
//注册http和https请求
Registry<ConnectionSocketFactory> socketFactoryRegistry = registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext))
.build();
//获取HttpClient池管理者
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//初始化httpClient
httpclient = HttpClients.custom().setConnectionManager(connManager).build();
}catch(KeyManagementException e){
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}; /**
* 创建httpsClientUtil对象
* @return
*/
public static HttpsClientUtil getInstance(){
if(httpsClientUtil==null){
httpsClientUtil = new HttpsClientUtil();
}
return httpsClientUtil;
} /**
* 描述: 发送post or get请求并获取结果
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public JSONObject sendRequest(String requestUrl, String requestMethod, String outputStr){
String responseObj = null;
CloseableHttpResponse execute = null;
try{
if("POST".equals(requestMethod)){
HttpPost httpPost = new HttpPost(requestUrl);
httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON);
// 将JSON字符串进行UTF-8编码,以便传输中文
StringEntity requestEntity = new StringEntity(outputStr,HttpsClientUtil.UTF8);
httpPost.setEntity(requestEntity);
execute = httpclient.execute(httpPost);
}else{
HttpGet httpGet = new HttpGet(requestUrl);
httpGet.addHeader(CONTENT_TYPE, APPLICATION_JSON);
execute = httpclient.execute(httpGet);
}
HttpEntity responseEntity = execute.getEntity();
if(responseEntity!=null){
responseObj = EntityUtils.toString(responseEntity,HttpsClientUtil.UTF8);
}
}catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
//关闭响应流
if(execute!=null) execute.close();
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("远程接口响应:"+responseObj);
return JSONObject.fromObject(responseObj);
} /**
* 描述: 发送post请求并获取结果
* @param requestUrl 请求地址
* @param requestUrlParam 请求地址拼接参数
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public JSONObject sendPostRequest(String requestUrl,Map<String,String> requestUrlParam, String outputStr){
return sendRequest(requestUrlParam(requestUrl, requestUrlParam), "POST", outputStr);
} /**
* 描述: 发送get请求并获取结果
* @param requestUrl 请求地址
* @param requestUrlParam 请求地址拼接参数
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public JSONObject sendGetRequest(String requestUrl,Map<String,String> requestUrlParam){
return sendRequest(requestUrlParam(requestUrl, requestUrlParam), "GET", null);
} /**
* 描述:拼接URL后接参数
* @param requestUrl 请求地址
* @param requestUrlParam 请求地址拼接参数
* @return 带参数请求地址
*/
public String requestUrlParam(String requestUrl,Map<String,String> requestUrlParam){
if(requestUrlParam==null){
return requestUrl;
}
String requestParam = "";
for (Entry<String, String> entry : requestUrlParam.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
requestParam += "&"+key+"="+value;
}
if(requestParam.length()>0){
if(requestUrl.indexOf("?")==-1){
requestUrl = requestUrl+"?"+requestParam.substring(1);
}else{
requestUrl = requestUrl+requestParam;
}
}
return requestUrl;
} }

带SSL证书的httpclient 远程接口工具类的更多相关文章

  1. Java模拟http请求调用远程接口工具类

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  2. HttpClient远程接口调用-实名认证

    1.HttpClient远程接口调用 1)用户注册 注册按钮button提交表单时,要return false form表单 <!-- action="http://localhost ...

  3. Spring 远程调用工具类RestTemplateUtils

    Spring 远程调用Rest服务工具类,包含Get.Post.Put.Delete四种调用方式. 依赖jar <dependency> <groupId>org.spring ...

  4. Utils--前台调用后台接口工具类

    Utils--前台调用后台接口工具类 package com.taotao.manage.httpclient; import java.io.IOException; import java.net ...

  5. HttpClient 远程接口调用方式

    远程接口调用方式HttpClient 问题:现在我们已经开发好了接口了,那该如何调用这个接口呢? 答:使用Httpclient客户端.   Httpclient简介 什么是httpclient Htt ...

  6. SSL证书详解和CFSSL工具使用

    公钥基础设施(PKI) 基础概念 CA(Certification Authority)证书,指的是权威机构给我们颁发的证书. 密钥就是用来加解密用的文件或者字符串.密钥在非对称加密的领域里,指的是私 ...

  7. 带jsk证书,请求https接口

    首先是三个返回的实体类 BaseVo.java package https2; import java.io.Serializable; import java.lang.reflect.Invoca ...

  8. 用nodejs快速实现websocket服务端(带SSL证书生成)

    有不少公司将nodejs的socket.io作为websocket的解决方案,很遗憾的是socket.io是对websocket的封装,并不支持html5原始的websocket协议,微信小程序使用的 ...

  9. HTTP接口开发专题二(发送http请求的接口工具类)

    import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; imp ...

随机推荐

  1. 细说多线程之Thread VS Runnable

    [线程创建的两种方式] [线程的生命周期] ● 就绪:创建了线程对象后,调用了线程的start(). (注意:此时线程只是进入了线程队列,等待获取CPU服务,具备了运行的条件,但并不一定已经开始运行了 ...

  2. js获取上个月的第一天和最后一天

    var now = new Date(); var fd = new Date(now.getFullYear(), now.getMonth()-1 ,1).toLocaleDateString() ...

  3. 【BZOJ4439】[Swerc2015]Landscaping 最小割

    [BZOJ4439][Swerc2015]Landscaping Description FJ有一块N*M的矩形田地,有两种地形高地(用‘#’表示)和低地(用‘.’表示) FJ需要对每一行田地从左到右 ...

  4. 纯java实现邮件发送服务(亲测好用)

    今天自己测试了一下用java代码实现发送有限的服务,非常简单.直接贴代码: import com.sun.mail.util.MailSSLSocketFactory; import javax.ma ...

  5. 如何设置,使IntelliJ IDEA智能提示忽略大小写

  6. finereport-JS

    JS实现定时刷新报表 setInterval("self.location.reload();",10000); //10000ms即每10s刷新一次页面. 注:对于cpt报表,若 ...

  7. 巨蟒python全栈开发-第18天 核能来袭-类和类之间的关系

    一.今日主要内容: 1.类与类之间的关系 在我们的世界中事物和事物之间总会有一些联系. 在面向对象中,类和类之间也可以产生相关的关系 (1)依赖关系 执行某个动作(方法)的时候,需要xxx来帮助你完成 ...

  8. 巨蟒python全栈开发数据库前端7:jQuery框架

    每个人的标准不同,看法等等,认识,价值观有所不同,促成了这些矛盾. 1.select例子 <!DOCTYPE html> <html lang="en"> ...

  9. MVC异步消息推送机制

    在MVC里面,有异步控制器,可以实现模拟消息推送机制功能 1.控制器要继承至AsyncController,如 public class RealTimeController : AsyncContr ...

  10. ubuntu微信

    方法1 – 使用Snap来安装微信 依次在terminal 执行一下命令 sudo apt install snapd snapd-xdg-open sudo snap install electro ...