一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。

import com.qunar.payment.gateway.front.channel.mpgs.po.HttpReqEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
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.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate; /**
* User:xfyou Date:2017/11/23 10:50
*/
public class HttpUtil {
private HttpUtil() {
} private static CredentialsProvider credentialsProvider;
private static final SSLConnectionSocketFactory SOCKET_FACTORY = getSocketFactory();
private static final NoopHostnameVerifier NO_OP = new NoopHostnameVerifier(); public static String execute(HttpReqEntity httpReqEntity) throws IOException {
CloseableHttpClient httpclient = getClosableHttpClient(httpReqEntity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(getHttpUriRequest(httpReqEntity));
return EntityUtils.toString(response.getEntity());
} finally {
try {
if (null != response) response.close();
if (null != httpclient) httpclient.close();
} catch (IOException ignored) {
}
}
} private static TrustManager getTrustManagers() {
return new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
} public void checkClientTrusted(X509Certificate[] certs, String authType) {
} public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
};
} private static SSLConnectionSocketFactory getSocketFactory() {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance(MpgsConstant.SECURITYPROTOCOL_VERSION_TLS_1_2);
} catch (NoSuchAlgorithmException e) {
return null;
}
try {
sslContext.init(null, new TrustManager[]{getTrustManagers()}, new SecureRandom());
} catch (KeyManagementException e) {
return null;
}
return new SSLConnectionSocketFactory(sslContext);
} private static CloseableHttpClient getClosableHttpClient(HttpReqEntity entity) {
return HttpClients.custom()
.setSSLSocketFactory(SOCKET_FACTORY)
.setSSLHostnameVerifier(NO_OP)
.setDefaultCredentialsProvider(getCredentialsProvider(entity.getCredUserName(), entity.getCredPasswd()))
.build();
} private static HttpPut getHttpPut(String requestUrl, String requestMessage, RequestConfig config) {
HttpPut httpPut = new HttpPut(requestUrl);
httpPut.setConfig(config);
httpPut.addHeader(HttpHeaders.CONTENT_TYPE, MpgsConstant.CONTENTTYPE_JSON);
httpPut.setEntity(new StringEntity(requestMessage, MpgsConstant.CHARSET_UTF8));
return httpPut;
} private static HttpGet getHttpGet(String requestUrl, RequestConfig config) {
HttpGet httpGet = new HttpGet(requestUrl);
httpGet.setConfig(config);
return httpGet;
} private static HttpUriRequest getHttpUriRequest(HttpReqEntity entity) {
return entity.getHttpMethod() == HttpMethod.GET ? getHttpGet(entity.getRequestUrl(), entity.getRequestConfig())
: getHttpPut(entity.getRequestUrl(), entity.getRequestMessage(), entity.getRequestConfig());
} private static CredentialsProvider getCredentialsProvider(String userName, String passwd) {
if (null == credentialsProvider) {
synchronized (HttpUtil.class) {
if (null == credentialsProvider) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, passwd));
credentialsProvider = credsProvider;
}
}
}
return credentialsProvider;
}
}

一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。的更多相关文章

  1. 网络相关系列之中的一个:Android中使用HttpClient发送HTTP请求

    一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是 ...

  2. HttpClientUtil [使用apache httpclient模拟http请求]

    基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...

  3. 170314、工具:apache httpClient多线程并发情况下安全实用及工具类分享

    简单用法介绍:介绍来源网络 建立连接:在HttpClient中使用多线程的一个主要原因是可以一次执行多个方法.在执行期间,每一个方法都使用一个HttpConnection实例.由于在同一时间多个连接只 ...

  4. 新旧apache HttpClient 获取httpClient方法

    在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...

  5. Apache HttpClient组件封装工具类

    package com.mengyao.spider.utils; import java.util.ArrayList;import java.util.HashMap;import java.ut ...

  6. Apache HttpClient使用之阻塞陷阱

    前言: 之前做个一个数据同步的定时程序. 其内部集成了某电商的SDK(简单的Apache Httpclient4.x封装)+Spring Quartz来实现. 原本以为简单轻松, 喝杯咖啡就高枕无忧的 ...

  7. Apache HttpClient 读取响应乱码问题总结

    Apache HttpClient 读取响应乱码问题总结 setCharacterEncoding  Content-Type  HttpClient  起因 最近公司产品线研发人员调整,集中兵力做战 ...

  8. 如何在Apache HttpClient中设置TLS版本

    1.简介 Apache HttpClient是一个底层.轻量级的客户端HTTP库,用于与HTTP服务器进行通信. 在本教程中,我们将学习如何在使用HttpClient时配置支持的传输层安全(TLS)版 ...

  9. 论httpclient上传带参数【commons-httpclient和apache httpclient区别】

    需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...

随机推荐

  1. [转]CENTOS 使用RSYNC+INOTIFY实现文件实时自动同步

    FROM : http://www.qiansw.com/centos-rsync-inotify-file-sync.html 生产环境中的两台web服务器,有个目录需要完全一样.使用rsync和i ...

  2. Kafka深度解析(如何在producer中指定partition)(转)

    原文链接:Kafka深度解析 背景介绍 Kafka简介 Kafka是一种分布式的,基于发布/订阅的消息系统.主要设计目标如下: 以时间复杂度为O(1)的方式提供消息持久化能力,即使对TB级以上数据也能 ...

  3. 【总结】关于MediaPlayer中的getCurrentPosition()和seekTo(int)的总结

    在使用音频时,需要用到MediaPlayer,除了一些基础的方法之外,比较难掌握的就是设计播放点的调转的地方,进过反复调试,我最终找到一个可以让getCurrentPosition()和seekTo( ...

  4. 排序算法的实现(归并,快排,堆排,希尔排序 O(N*log(N)))

    今天跟着左老师的视频,理解了四种复杂度为 O(N*log(N))的排序算法,以前也理解过过程,今天根据实际的代码,感觉基本的算法还是很简单的,只是自己写的时候可能一些边界条件,循环控制条件把握不好. ...

  5. iOS开发-View中frame和bounds区别

    开发中调整View的时候的经常会遇到frame和bounds,刚开始看的时候不是很清楚,不过看了一下官方文档,frame是确定视图在父视图中的位置,和本身的大小,bounds确定可以确定子视图在当前视 ...

  6. mybatis 乐观锁和逻辑删除

    本篇介绍easymybatis如配置乐观锁和逻辑删除. 乐观锁 easymybatis提供的乐观锁使用方式跟JPA一样,使用@Version注解来实现.即:数据库增加一个int或long类型字段ver ...

  7. 关于使用rem单位、css函数calc()进行自适应布局

    一.关于css中的单位 大家都知道在css中的单位,一般都包括有px,%,em等单位,另外css3新增加一个单位rem. 其中px,%等单位平时在传统布局当中使用的比较频繁,大家也比较熟悉,不过px单 ...

  8. Android WindowManager实现悬浮窗效果 (一)——与当前Activity绑定

    最近有学生做毕业设计,想使用悬浮窗这种效果,其实很简单,我们可以通过系统服务WindowManager来实现此功能,本章我们来试验一下在当前Activity之上创建一个悬浮的view. 第一步:认识W ...

  9. 大数据开发实战:Storm流计算开发

    Storm是一个分布式.高容错.高可靠性的实时计算系统,它对于实时计算的意义相当于Hadoop对于批处理的意义.Hadoop提供了Map和Reduce原语.同样,Storm也对数据的实时处理提供了简单 ...

  10. win7基于mahout推荐之用户相似度计算

    http://www.douban.com/note/319219518/?type=like win7基于mahout推荐之用户相似度计算 2013-12-03 09:19:11    事情回到半年 ...