一个封装的使用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. Mac环境配置 - iOS开发人员 -待续

    Mac环境记录 Mac 相关 目录相关 显示: $ defaults write com.apple.finder AppleShowAllFiles -bool true 隐藏: $ default ...

  2. 深入理解多线程(二)—— Java的对象模型

    上一篇文章中简单介绍过synchronized关键字的方式,其中,同步代码块使用monitorenter和monitorexit两个指令实现,同步方法使用ACC_SYNCHRONIZED标记符实现.后 ...

  3. Reader 与 Guava MultiReader

    Reader是Java IO体系里字符处理读取流的基本类,代码如下 /* * %W% %E% * * Copyright (c) 2006, Oracle and/or its affiliates. ...

  4. Log Shipping搭建

    1.    概述 SQL Server 使用日志传送,您可以自动将“主服务器”实例上“主数据库”内的事务日志备份发送到单独“辅助服务器”实例上的一个或多个“辅助数据库”.事务日志备份分别应用于每个辅助 ...

  5. 算法: skiplist 跳跃表代码实现和原理

    SkipList在leveldb以及lucence中都广为使用,是比较高效的数据结构.由于它的代码以及原理实现的简单性,更为人们所接受. 所有操作均从上向下逐层查找,越上层一次next操作跨度越大.其 ...

  6. Windows server 2012 R2 与 Windows 2016 的双系统重启选项

    一台主机上,同时安装了Windows 2012R2还有Windows 2016, 但是如何能在任意一个系统重启到另一个呢? 下图中,在Win2012R2中,无法选择重启到2016中. 解决方案 === ...

  7. Http协议中Get和Post的浅谈

    起名困难户,每次写文章最愁的就是不知道该如何起个稍具内涵的名字,如果这篇文章我只是写写Get和Post的区别,我可以起个名字“Get和Post的那点事”,如果打算阐述一下Http协议原理性内容,那该叫 ...

  8. 超级简单!80行代码实现Google日历(拖放、移动、AJAX)

    行代码实现Google日历 Introduction 本实例介绍使用DayPilot Lite for ASP.NET MVC library 类来实现类google日历效果. 在线实例 天视图  星 ...

  9. 大数据开发实战:Stream SQL实时开发一

    1.流计算SQL原理和架构 流计算SQL通常是一个类SQL的声明式语言,主要用于对流式数据(Streams)的持续性查询,目的是在常见流计算平台和框架(如Storm.Spark Streaming.F ...

  10. JPA(二):HellWord工程

    使用JPA持久化对象的操作步骤: 1)创建persistence.xml,在这个文件中配置持久化单元: --- 需要指定跟哪个数据库进行交互: --- 需要指定JPA使用哪个持久化的框架以及配置该框架 ...