一个封装的使用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. Android:客户端和服务器之间传输数据加密

    Android客户端与服务器进行数据传输时,一般会涉及到两类数据的加密情况,一类是只有创建者才能知道的数据,比如密码:另一类是其他比较重要的,但是可以逆向解密的数据. 第一类:密码类的数据,为了让用户 ...

  2. HTML5 本地文件操作之FileSystemAPI实例(一)

    文件操作实例整理一 1.请求系统配额类型 console.info(window.TEMPORARY); //0 临时 console.info(window.PERSISTENT); //1 持久 ...

  3. ASP.NET Core开发-读取配置文件Configuration appsettings.json

    https://www.cnblogs.com/linezero/p/Configuration.html ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配 ...

  4. IDEA重写toString()模板,转成json格式

    1.类中Alt + Insert,弹出下框 2.点击新增 public java.lang.String toString() { final java.lang.StringBuilder sb = ...

  5. 也给我的E420拆机清清灰尘

    用了两年,天气燥热,是得拆开清理下了,E430清理非常方便,拆开后面挡板就行,E420就麻烦很多,需要全部拆下,关于E420的拆机网上已经有非常详细的教程了,我这里做一些补充,有兴趣的同学欢迎参考. ...

  6. go语言之进阶篇Ticker的使用

    Ticker是一个定时触发的计时器,它会以一个间隔(interval)往channel发送一个事件(当前时间),而channel的接收者可以以固定的时间间隔从channel中读取事件. 1.Ticke ...

  7. 轻松搞定 easyui datagrid 二次加载的问题(转)

    对于使用url方式的初学者,经常碰到重复请求的问题,这个问题的根源是因为一旦设置了url参数,Datagrid组件在实例化的时候就会做请求,如何避免二次加载这样问题呢,个人觉得注意以下两点基本就可以防 ...

  8. 构建配置 ProGuard Shrink 混淆和压缩

    官方文档 压缩代码和资源 要尽可能减小 APK 文件,您应该启用压缩来移除 release build 中未使用的代码和资源.此页面介绍如何执行该操作,以及如何指定要在构建时保留或舍弃的代码和资源. ...

  9. 我对android davilk 虚拟机的理解

    Davilk虚拟机作为Android平台的一部分.Google公司花了大量时间思考针对低功耗手持设备的优化设计.在智能手机出现之前,与桌面设备相比,手持设备在内存和速度方面落后8-10年.它们的计算能 ...

  10. python3 特殊字符处理 \x06\x05\x07

    最近在处理Excel文件中,报错:openpyxl.utils.exceptions.IllegalCharacterError, 原因是某字段出现特殊字符 \x05,\x06,\x07如下图: 在E ...