import java.io.IOException;
import java.nio.charset.Charset;
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 javax.net.ssl.SSLContext; import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
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.utils.URIBuilder;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; public class HttpClient { private final static String ENCODE = "utf-8"; private final static Charset CHARSET = Charset.forName("utf-8"); private final static int SOCKET_TIME_OUT = 12000; private final static int SOCKET_CONNECT_OUT = 12000; private final static int CONNECTION_REQUEST_OUT = 12000; private static RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT)
.setConnectTimeout(SOCKET_CONNECT_OUT).setConnectionRequestTimeout(CONNECTION_REQUEST_OUT).build(); private static ObjectMapper objectMapper = new ObjectMapper(); private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); @SuppressWarnings("deprecation")
public static SSLConnectionSocketFactory sslInit() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
return true;
}
}).build(); } catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return new SSLConnectionSocketFactory(sslContext);
} /**
* @Description post请求函数
* @param scheme http/https
* @param host 请求域名
* @param path 请求路径
* @param params URL请求参数
* @param jsonBody HTTP请求BODY
* @param headers HTTP请求头部
* @return
*/
public static HashMap post(String scheme, String host, String path, Map<String, String> params, String jsonBody, Map<String, String> headers) {
HashMap resultMap = new HashMap();
CloseableHttpClient closeableHttpClient = null;
try {
SSLConnectionSocketFactory sslsf = sslInit();
closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).setSSLSocketFactory(sslsf).build(); //添加URL参数
List<NameValuePair> values = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (String s : params.keySet()) {
values.add(new BasicNameValuePair(s, params.get(s)));
}
}
//创建URI
java.net.URI uri = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPath(path)
.setParameters(values)
.build(); HttpPost httpPost = new HttpPost(uri);
//添加头部
if (headers != null && !headers.isEmpty()) {
for (String s : headers.keySet()) {
httpPost.addHeader(s, headers.get(s));
}
}
//添加URL参数
/*if (params != null && !params.isEmpty()) {
List<NameValuePair> values = new ArrayList<NameValuePair>();
for (String s : params.keySet()) {
values.add(new BasicNameValuePair(s, params.get(s)));
}
httpPost.setEntity(new UrlEncodedFormEntity(values, ENCODE));
}*/ //添加请求BODY
if (jsonBody != null) {
httpPost.setEntity(new StringEntity(jsonBody, Charset.forName("utf-8")));
} LOG.info("HTTP Request URI:{}",httpPost.getURI().toString());
LOG.info("HTTP Request Body: {}",jsonBody); //发出请求
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, ENCODE);
LOG.info("HTTP Response:{}",content); if(StringUtils.isNotBlank(content)){
resultMap = objectMapper.readValue(content, HashMap.class);
}
} catch (Exception e) {
LOG.info("Error msg:[{}]",e.getMessage());
e.printStackTrace();
} finally {
try {
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultMap;
} /**
* @Description http get请求函数
* @param scheme http/https
* @param host 域名
* @param path 资源路径
* @param params 请求参数
* @param headers 请求头部
* @return
*/
public static HashMap get(String scheme, String host, String path, Map<String, String> params, Map<String, String> headers) {
HashMap resultMap = new HashMap();
CloseableHttpClient closeableHttpClient = null;
try {
SSLConnectionSocketFactory sslsf = sslInit();
closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(defaultRequestConfig).setSSLSocketFactory(sslsf).build(); //添加URL参数
List<NameValuePair> values = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (String s : params.keySet()) {
values.add(new BasicNameValuePair(s, params.get(s)));
}
} //创建URI
java.net.URI uri = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPath(path)
.setParameters(values)
.build(); LOG.info("URI is:{}",uri.toString());
//创建GET请求对象
HttpGet httpGet = new HttpGet(uri); //添加头部
if (headers != null && !headers.isEmpty()) {
for (String s : headers.keySet()) {
httpGet.addHeader(s, headers.get(s));
}
} //发出请求
LOG.info("HTTP Request:{}",httpGet.getURI().toString());
CloseableHttpResponse response = closeableHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, ENCODE);
LOG.info("HTTP Response:{}",content); if(StringUtils.isNotBlank(content)){
resultMap = objectMapper.readValue(content, HashMap.class);
}
} catch (Exception e) {
LOG.info("Error msg:[{}]",e.getMessage());
e.printStackTrace();
} finally {
try {
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultMap;
} }

最新文章

  1. Beta版本冲刺总汇
  2. RFID第二次作业
  3. 12.iscsi-target
  4. int.class与Integer.type的不同
  5. Search Insert Position--寻找插入点Given a sorted array and a target value, return the index if the target
  6. 一步一步学android之事件篇——单选按钮监听事件
  7. SharePoint 2013 如何使用Silverlight
  8. H5个性三级联动日期插件(一)
  9. [leetcode-500-Keyboard Row]
  10. java线程池相关知识点总结
  11. ios GCD将异步转换为同步
  12. 阿里Canal安装和代码示例
  13. php foreach跳出本次/当前循环与终止循环方法
  14. PHP文件管理—实现网盘以及压缩包的功能操作
  15. 最大团&amp;优化
  16. Oracle 相关概念
  17. 读取excel合并单元格内容
  18. hihocoder 1638:多级并查集
  19. 基于Vue的简单通用分页组件
  20. ios 中是否每一个对象(尤其是在使用多线程时),都要判断一下对象是否为nil,以防止程序闪退?

热门文章

  1. git分布式版本控制系统权威指南学习笔记(一):配置文件、简单流程和小问题
  2. git clone后切换分支,和远端的不一样。
  3. python_way day14 CSS,莫泰对话框
  4. Linux源码与编译出的目标文件汇编代码的一致性问题
  5. Git 学习第二天(三)
  6. Django框架(三)—— orm增删改查、Django生命周期
  7. 前端(十六)—— JavaScript盒子模型、JS动画、DOM、BOM
  8. Laravel/php 一些调试技巧
  9. Apache版hadoop编译
  10. react-router踩坑