httpClient连接工具类实测可用
package com.jeecms.common.util; import com.google.gson.Gson;
import com.jeecms.cms.api.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.methods.HttpRequestBase;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ssl.SSLSocketFactory;
import sun.java2d.opengl.OGLContext; import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
/**
* @ Author :YanTingXiang
* @ Date :Created in 2019-06-10
* @ Description:
* @Version : 1.0
*/
@Slf4j
public class HttpClientUtil {
@Resource
private Gson gson; private static HttpClientUtil instance;
protected Charset charset;
private int timeOut=10000;//10s download not set timeout public static DefaultHttpClient getHttpsClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
} public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
} public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
} };
DefaultHttpClient client = new DefaultHttpClient();
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx); ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
// 设置要使用的端口,默认是443
sr.register(new Scheme("https", 443, ssf));
return client;
} catch (Exception ex) {
return null;
}
} private HttpClientUtil(){} public static HttpClientUtil getInstance() {
return getInstance(Charset.defaultCharset());
} public static HttpClientUtil getInstance(Charset charset){
if(instance == null){
instance = new HttpClientUtil();
}
instance.setCharset(charset);
return instance;
} public void setCharset(Charset charset) {
this.charset = charset;
} /**
* post请求
*/
public String doPost(String url) throws Exception {
return doPost(url, null, null);
}
public String doPostByHeader(String url,Map<String, String> header) throws Exception {
return doPost(url, null, header);
}
public String doPost(String url, Map<String, Object> params) throws Exception {
return doPost(url, params, null);
} public String doPost(String url, Map<String, Object> params, Map<String, String> header) throws Exception {
String body = null;
try {
// Post请求
log.debug(" protocol: POST");
log.debug(" url: " + url);
HttpPost httpPost = new HttpPost(url.trim());
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut) .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpPost.setConfig(requestConfig);
// 设置参数
if (null != params && !header.isEmpty()){
log.debug(" params: " + gson.toJson(params));
httpPost.setEntity(new UrlEncodedFormEntity(map2NameValuePairList(params), charset));
}
// 设置Header
if (header != null && !header.isEmpty()) {
log.debug(" header: " + header.get(Constants.HEADER_KEY_TOKEN));
for (Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = (Entry<String, String>) it.next();
httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// 发送请求,获取返回数据
body = execute(httpPost);
} catch (Exception e) {
throw e;
}
log.debug(" result: " + body);
return body;
} /**
* postJson请求
*/
public String doPostJson(String url, Map<String, Object> params) throws Exception {
return doPostJson(url, params, null);
} public String doPostJson(String url, Map<String, Object> params, Map<String, String> header) throws Exception {
String json = null;
if (params != null && !params.isEmpty()) {
for (Iterator<Entry<String, Object>> it = params.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = (Entry<String, Object>) it.next();
Object object = entry.getValue();
if (object == null) {
it.remove();
}
}
json = gson.toJson(params);
//json = JSON.toJSON(params);
}
return postJson(url, json, header);
} public String doPostJson(String url, String json) throws Exception {
return doPostJson(url, json, null);
} public String doPostJson(String url, String json, Map<String, String> header) throws Exception {
return postJson(url, json, header);
} private String postJson(String url, String json, Map<String, String> header) throws Exception {
String body = null;
try {
// Post请求
log.debug(" protocol: POST");
log.debug(" url: " + url);
HttpPost httpPost = new HttpPost(url.trim());
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut) .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpPost.setConfig(requestConfig);
// 设置参数
log.debug(" params: " + json);
StringEntity entity = new StringEntity(json, ContentType.DEFAULT_TEXT.withCharset(charset));
httpPost.setEntity(entity);
httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
log.debug(" type: JSON");
// 设置Header
if (header != null && !header.isEmpty()) {
log.debug(" header: " + gson.toJson(header));
for (Iterator<Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = (Entry<String, String>) it.next();
httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// 发送请求,获取返回数据
body = execute(httpPost);
} catch (Exception e) {
throw e;
}
log.debug(" result: " + body);
return body;
} /**
* get请求
*/
public String doGet(String url) throws Exception {
return doGet(url, null, null);
} public String doGet(String url, Map<String, String> header) throws Exception {
return doGet(url, null, header);
} public String doGet(String url, Map<String, Object> params, Map<String, String> header) throws Exception {
String body = null;
try {
// Get请求
log.debug("protocol: GET");
HttpGet httpGet = new HttpGet(url.trim());
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut) .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpGet.setConfig(requestConfig);
// 设置参数
if (params != null && !params.isEmpty()) {
String str = EntityUtils.toString(new UrlEncodedFormEntity(map2NameValuePairList(params), charset));
String uri = httpGet.getURI().toString();
if(uri.indexOf("?") >= 0){
httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str));
}else {
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
}
}
log.debug(" url: " + httpGet.getURI());
// 设置Header
if (header != null && !header.isEmpty()) {
log.debug(" header: " + header);
for (Iterator<Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = (Entry<String, String>) it.next();
httpGet.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// 发送请求,获取返回数据
body = execute(httpGet);
} catch (Exception e) {
throw e;
}
log.debug(" result: " + body);
return body;
} /**
* 下载文件
*/
public void doDownload(String url, String path) throws Exception {
download(url, null, path);
} public void doDownload(String url, Map<String, Object> params, String path) throws Exception {
download(url, params, path);
} /**
* 上传文件
*/
public String doUpload(String url, String name, String path) throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put(name, new File(path));
return doUpload(url, params);
} public String doUpload(String url, Map<String, Object> params) throws Exception {
String body = null;
// Post请求
HttpPost httpPost = new HttpPost(url.trim());
// 设置参数
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setCharset(charset);
if (params != null && !params.isEmpty()) {
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Object value = params.get(key);
if (value instanceof File) {
FileBody fileBody = new FileBody((File) value);
entityBuilder.addPart(key, fileBody);
} else {
entityBuilder.addPart(key, new StringBody(String.valueOf(value), ContentType.DEFAULT_TEXT.withCharset(charset)));
}
}
}
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
// 发送请求,获取返回数据
body = execute(httpPost);
return body;
} private void download(String url, Map<String, Object> params, String path) throws Exception {
// Get请求
HttpGet httpGet = new HttpGet(url.trim());
if (params != null && !params.isEmpty()) {
// 设置参数
String str = EntityUtils.toString(new UrlEncodedFormEntity(map2NameValuePairList(params)));
String uri = httpGet.getURI().toString();
if (uri.indexOf("?") >= 0) {
httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str));
} else {
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str));
}
}
// 发送请求,下载文件
downloadFile(httpGet, path);
} private void downloadFile(HttpRequestBase requestBase, String path) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
CloseableHttpResponse response = httpclient.execute(requestBase);
try {
HttpEntity entity = response.getEntity(); if (entity != null) {
byte[] b = EntityUtils.toByteArray(entity);
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(path)));
out.write(b);
out.flush();
out.close();
}
EntityUtils.consume(entity);
} catch (Exception e) {
throw e;
} finally {
response.close();
}
} catch (Exception e) {
throw e;
} finally {
httpclient.close();
}
} private String execute(HttpRequestBase requestBase) throws Exception {
CloseableHttpClient httpclient = getHttpsClient();
HttpParams params=httpclient.getParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeOut);
String body = null;
try {
CloseableHttpResponse response = httpclient.execute(requestBase);
try {
HttpEntity entity = response.getEntity(); if (entity != null) {
body = EntityUtils.toString(entity, charset.toString());
}
EntityUtils.consume(entity);
} catch (Exception e) {
throw e;
}finally {
response.close();
}
} catch (Exception e) {
throw e;
} finally {
httpclient.close();
}
return body;
} private List<NameValuePair> map2NameValuePairList(Map<String, Object> params) {
if (params != null && !params.isEmpty()) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if(params.get(key) != null) {
String value = String.valueOf(params.get(key));
list.add(new BasicNameValuePair(key, value));
}
}
return list;
}
return null;
} public void downLoad(String url, String localFileName) {
DefaultHttpClient httpClient = new DefaultHttpClient();
OutputStream out = null;
InputStream in = null; try {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
in = entity.getContent(); long length = entity.getContentLength();
if (length <= 0) {
System.out.println("下载文件不存在!");
return;
} System.out.println("The response value of token:" + httpResponse.getFirstHeader("token")); File file = new File(localFileName);
if(!file.exists()){
file.createNewFile();
} out = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int readLength = 0;
while ((readLength=in.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
out.write(bytes);
} out.flush(); }catch (Exception e){
e.printStackTrace();
}finally{
try {
if(in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
} try {
if(out != null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} }
httpClient连接工具类实测可用的更多相关文章
- android开发网络连接工具类(一)
网络连接工具类整理: package com.gzcivil.utils; import java.io.IOException; import java.util.ArrayList; import ...
- Sublime3和Chrome配置自动刷新网页【实测可用】
SublimeText2下的LiveReload在SublimeText3下无法正常使用,本文整理SublimeText3安装LiveReload的方法.win7下实测可用! 安装成功后,就不需要再手 ...
- 实测可用的免费STUN服务器!
实测可用的免费STUN服务器! 以实际ping延迟排序: stun.voipbuster.com 287ms stun.wirlab.net 320ms s1.taraba.net ...
- 数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java
package com.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepare ...
- 数据库连接工具类 数据库连接工具类——仅仅获得连接对象 ConnDB.java
package com.util; import java.sql.Connection; import java.sql.DriverManager; /** * 数据库连接工具类——仅仅获得连接对 ...
- 刚破了潘金莲的身份信息(图片文字识别),win7、win10实测可用(免费下载)
刚破了潘金莲的身份信息(图片文字识别),win7.win10实测可用 效果如下: 证照,车牌.身份证.名片.营业执照 等图片文字均可识别 电脑版 本人出品 大小1.3MB 下载地址:https://p ...
- JDBC实例--通过连接工具类DBUtil +配置文件来获取连接数据库,方便又快捷
根据前面的连接方法,还有缺点就是,如果人家要换数据库,还得改动源代码,然后还要编译什么的.这样客户修改也不容易. 做法:我们写一个配置文件,把该数据写在配置文件上面,然后通过类来加载改文件,然后读取相 ...
- Java开发小技巧(五):HttpClient工具类
前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...
- Redis连接工具类
Redis连接工具类 导包 测试一下(junit) package com.test; import org.junit.Test; import redis.clients.jedis.Jedis; ...
随机推荐
- (转)Kubernetes 配置Pod和容器(十七) 使用Secrets管理安全证书
转:https://www.jianshu.com/p/530b3642c642 本章节展示了如何把密码秘钥等敏感数据安全的注入到Pod里面. 转换安全数据成base-64表示 假设你有两个秘密数据: ...
- HDU6415 Rikka with Nash Equilibrium
HDU6415 Rikka with Nash Equilibrium 找规律 + 大数 由于规律会被取模破坏,所以用了java 找出规律的思路是: 对于一个n*m的矩阵构造,我先考虑n*1的构造,很 ...
- 007-TreeMap、Map和Bean互转、BeanUtils.copyProperties(A,B)拷贝、URL编码解码、字符串补齐,随机字母数字串
一.转换 1.1.TreeMap 有序Map 无序有序转换 使用默认构造方法: public TreeMap(Map<? extends K, ? extends V> m) 1.2.Ma ...
- windows10上使用一个tomcat部署2个项目
前言:目前想在本机部署2个项目,网上查了之后,写下本篇随笔 1.准备工作 2.操作方法 3.运行2个项目 1.准备工作 2个war包(一个jprss.war和一个jenkins.war) 1个tomc ...
- Jenkins+GitLab持续集成
向GitLab提交代码之后自动触发Jenkins构建 https://baijiahao.baidu.com/s?id=1630678692475452408&wfr=spider&f ...
- Vagrant 手册之网络 - 端口转发
原文地址 Vagrantfile 配置文件中端口转发的网络标识符:forwarded_port,例如: config.vm.network "forwarded_port", gu ...
- js面向对象程序设计之构造函数
再上一篇的开头说了创建对象的两种方式,一种是Object构造函数的方式,一种是对象字面量的方法.但这些方式创建多个对象的时候都会产生大量的重复代码.经过技术的进步也演化出来许多的创建对象的模式.本章会 ...
- 机器学习实战笔记-10-K均值聚类
K-均值聚类 优点:易实现.缺点:可能收敛到局部最小值,大规模数据集上收敛较慢:适用于数值型数据. K-均值聚类(找到给定数据集的k个簇) 算法流程 伪代码: 创建k个点作为起始质心(经常是随机选择) ...
- JavaWeb——servlet1
一.servlet简介 Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于 ...
- 4、、多变量线性回归(Linear Regression with Multiple Variables)
4.1 多维特征 目前为止,我们探讨了单变量/特征的回归模型,现在我们对房价模型增加更多的特征,例如房间数楼层等,构成一个含有多个变量的模型,模型中的特征为(x1,x2,...xn) 增添更多特征后, ...