HttpClientUtils.java
package com.vcredit.ddcash.batch.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.conn.ssl.SSLConnectionSocketFactory;
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.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HttpClientUtils
*/
public class HttpClientUtils {
/**
* 日志工具
*/
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
/**
* 5分钟
*/
public static final int MINUTE_FIVE = 300000;
/**
* 10分钟
*/
public static final int MINUTE_TEN = 600000;
/**
* HttpClient
*/
private static final HttpClient client = getInstance();
/**
* 让Httpclient支持https
*
* @return HttpClient
*/
private static HttpClient getInstance() {
X509TrustManager x509mgr = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance(SSLConnectionSocketFactory.SSL);
sslContext.init(null, new TrustManager[] { x509mgr }, null);
} catch (Exception e) {
logger.error("error to init httpclient", e);
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(400);// 客户端总并行链接最大数
connManager.setDefaultMaxPerRoute(40); // 每个主机的最大并行链接数
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(connManager);
httpClientBuilder.setSSLSocketFactory(sslsf);
return httpClientBuilder.build();
}
public static final RequestConfig getDefaultTimeOutConfig() {
return getTimeOutConfig(60000, 30000);
}
private static final RequestConfig getTimeOutConfig(int socketTimeout, int connectionTimeout) {
return RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectionTimeout).build();
}
/**
* Get方法查询
*/
public static String getMethodGetResponse(String address) throws Exception {
return getMethodGetResponse(address, getDefaultTimeOutConfig());
}
/**
* Post方法查询
*/
public static String getMethodPostResponse(String address, HttpEntity paramEntity) throws Exception {
RequestConfig config = getDefaultTimeOutConfig();
return getMethodPostResponse(address, paramEntity, config);
}
/**
* 自定义超时的Get方法查询
*/
public static String getMethodGetResponse(String address, int connectionTimeout, int socketTimeout) throws Exception {
return getMethodGetResponse(address, getTimeOutConfig(socketTimeout, connectionTimeout));
}
/**
* 自定义超时的Post方法
*/
public static String getMethodPostResponse(String address, HttpEntity paramEntity, int connectionTimeout, int socketTimeout) throws Exception {
RequestConfig config = getTimeOutConfig(socketTimeout, connectionTimeout);
return getMethodPostResponse(address, paramEntity, config);
}
/**
* Post Entity
*/
public static byte[] getMethodPostBytes(String address, HttpEntity paramEntity) throws Exception {
return getMethodPostContent(address, paramEntity, getDefaultTimeOutConfig());
}
/**
* HttpClient get方法请求返回Entity
*/
public static byte[] getMethodGetContent(String address) throws Exception {
return getMethodGetContent(address, getDefaultTimeOutConfig());
}
/**
* HttpClient Get方法请求数据
*/
private static String getMethodGetResponse(String address, RequestConfig config) throws Exception {
logger.info("Start Access Address(" + address + ") With Get Request");
byte[] result = getMethodGetContent(address, config);
return new String(result, "utf-8");
}
/**
* HttpClient Post方法请求数据
*/
private static String getMethodPostResponse(String address, HttpEntity paramEntity, RequestConfig config) throws Exception {
logger.info("Begin Access Url(" + address + ") By Post");
byte[] content = getMethodPostContent(address, paramEntity, config);
String result = new String(content, "utf-8");
logger.info("Response -> " + result);
return result;
}
/**
* HttpClient get方法请求返回Entity
*/
private static byte[] getMethodGetContent(String address, RequestConfig config) throws Exception {
HttpGet get = new HttpGet(address);
try {
logger.info("Start Access Address(" + address + ") With Get Request");
get.setConfig(config);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
int code = response.getStatusLine().getStatusCode();
throw new RuntimeException("HttpGet Access Fail , Return Code(" + code + ")");
}
response.getEntity().getContent();
return convertEntityToBytes(response.getEntity());
} finally {
if (get != null) {
get.releaseConnection();
}
}
}
/**
* Post Entity
*/
private static byte[] getMethodPostContent(String address, HttpEntity paramEntity, RequestConfig config) throws Exception {
HttpPost post = new HttpPost(address);
try {
if (paramEntity != null) {
post.setEntity(paramEntity);
}
post.setConfig(config);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
int code = response.getStatusLine().getStatusCode();
throw new RuntimeException("HttpPost Request Access Fail Return Code(" + code + ")");
}
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new RuntimeException("HttpPost Request Access Fail Response Entity Is null");
}
return convertEntityToBytes(entity);
} finally {
if (post != null) {
post.releaseConnection();
}
}
}
/**
* 转化返回为byte数组
*
* @param entity
* @return byte[]
* @throws Exception
*/
private static byte[] convertEntityToBytes(HttpEntity entity) throws Exception {
InputStream inputStream = null;
try {
if (entity == null || entity.getContent() == null) {
throw new RuntimeException("Response Entity Is null");
}
inputStream = entity.getContent();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
return out.toByteArray();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
/**
* 甜橙小贷发送消息工具
* @param path
* @param params
* @return
* @throws Exception
*/
public static String post(String path,String params) throws Exception{
if(path.startsWith("https")){
return https(path,params);
}else{
return http(path,params);
}
}
public static String http(String path,String params) throws Exception{
HttpURLConnection httpConn=null;
BufferedReader in=null;
PrintWriter out=null;
try {
URL url=new URL(path);
httpConn=(HttpURLConnection)url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
//发送post请求参数
out=new PrintWriter(httpConn.getOutputStream());
out.println(params);
out.flush();
//读取响应
if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){
StringBuffer content=new StringBuffer();
String tempStr="";
in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
while((tempStr=in.readLine())!=null){
content.append(tempStr);
}
return content.toString();
}else{
throw new Exception("请求出现了问题!");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
in.close();
out.close();
httpConn.disconnect();
}
return null;
}
public static String https(String path,String params) throws Exception {
String res = null;
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(path);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(2000).build();// 设置请求和传输超时时间
request.setConfig(requestConfig);
StringEntity myEntity = new StringEntity(params, "UTF-8");
try {
request.setEntity(myEntity);
CloseableHttpResponse response = client.execute(request);
res = EntityUtils.toString(response.getEntity());
return res;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("identitycard", request.getMobileAuthIdentity());
paramsMap.put("mobile", request.getMobile());
String paramJson = GsonUtils.toJson(paramsMap);
logger.info("isauthCollect->Request->" + paramJson);
String base64Content = Base64.encodeBase64String(paramJson.getBytes("utf-8"));
StringEntity paramEntity = new StringEntity(base64Content, "UTF-8");
String respJson = HttpClientUtils.getMethodPostResponse(url, paramEntity);
logger.info("isauthCollect->Response->" + respJson);
VBSCommonResponseDto result= GsonUtils.convertObj(respJson, VBSCommonResponseDto.class);
HttpClientUtils.java的更多相关文章
- Spring提供的用于访问Rest服务的客户端:RestTemplate实践
什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效 ...
- 调用外部接口支持https请求
1,创建RestTemplateConfig.java文件,内容如下: package com.htsec.monitor.internet.config;import com.htsec.monit ...
- 微信登录4-开发回调URL
一.准备 1.引入pom依赖 在要使用HttpClient的项目中加入依赖 <!--httpclient--> <dependency> <groupId>org. ...
- HttpClient客户端网络编程——高可用、高并发
本文是HttpClient的学习博客,RestTemplate是基于HttpClient的封装,feign可基于HttpClient进行网络通信. 那么作为较底层的客户端网络编程框架,该怎么配置使其能 ...
- SpringBoot+Maven 多模块项目的构建、运行、打包实战
前言 最近在做一个很复杂的会员综合线下线上商城大型项目,单模块项目无法满足多人开发和架构,很多模块都是重复的就想到了把模块提出来,做成公共模块,基于maven的多模块项目,也好分工开发,也便于后期微服 ...
- HttpClient 的Timeout waiting for connection from pool
Timeout waiting for connection from pool 异常 httpClient大家用到地方会很多,先简单描述一下几个关键配置的意义 httpClient版本为4.5.1 ...
- Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
- HttpClientUtils
import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.List; import ...
- 包括post,get请求(http,https)的HttpClientUtils
package cn.knet.data.untils; import java.io.IOException; import java.net.SocketTimeoutException; imp ...
随机推荐
- 判断App是否在后台运行
在一些场景中,经常会需要判断App是否在后台运行,比如是否显示解锁界面,收到新消息是否显示Notification等.需求可能是多样化的,但所依仗的原理是相通的,今天Stay打算说说这些需求的最优解. ...
- hdu2255 二分图最大权配KM
KM算法:hdu2255 (大概理解了 参考博客: http://blog.csdn.net/niushuai666/article/details/7171880) 所谓交错树:就是 ...
- css3 总结02
盒子尺寸 .border-box{ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; border-sizing: border ...
- 分享Kali Linux 2016.2第41周镜像虚拟机
分享Kali Linux 2016.2第41周镜像虚拟机该虚拟机使用Kali Linux 2016.2第41周镜像文件安装而成,系统已经更新到10月12日.里面已经进行如下配置:(1)设置官方软件源( ...
- 【Highcharts】 动态删除series
先绘制,后删除多余 var chart = new Highcharts.Chart(options); if (chart.series.length > result.dataList0.l ...
- HTML元素的offsetWidht、clientWidth、scrollWidth属性区别
每个HTML元素都有以下属性 offsetWidth:内容+内边距(padding)+边框+滚动条宽度,以css像素返回它的屏幕尺寸. offsetHeight:(同上) offsetLeft:如果o ...
- iOSDay27之界面通信
1. 属性传值(前面的界面给后面传值) 第一步: 在 SecondViewController.h 文件里定义一个存放传过来值的变量 contents #import <UIKit/UIKit. ...
- (转)HBase工程师线上工作经验总结----HBase常见问题及分析
阅读本文可以带着下面问题:1.HBase遇到问题,可以从几方面解决问题?2.HBase个别请求为什么很慢?你认为是什么原因?3.客户端读写请求为什么大量出错?该从哪方面来分析?4.大量服务端excep ...
- 修改文档框架:word-多级列表与标题样式相结合
转自:http://blog.sina.com.cn/s/blog_6721f25c0100nuf0.html 设置标题的时候希望出现多标题并且自动编号的标题,如下1. XXXXXXXXXXX ...
- Node.js -- Router模块中有一个param方法
这段时间一直有在看Express框架的API,最近刚看到Router,以下是我认为需要注意的地方: Router模块中有一个param方法,刚开始看得有点模糊,官网大概是这么描述的: 1 Map lo ...