httpcore4.4.10, httpclient4.5.6

 package com.test.http;

 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.http.Consts;
import org.apache.http.Header;
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.HttpPost;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.XML; import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map; public class HTTPUtils {
private static RequestConfig config; public HTTPUtils(){
config = RequestConfig.custom()
.setConnectionRequestTimeout(3000)
.setConnectTimeout(3000)
.setSocketTimeout(3000)
.build();
} /**
* 自定义超时时间
* @param connectionRequestTimeout 指从连接池获取连接的timeout
* @param connectTimeout 指客户端和服务器建立连接的timeout,超时后会ConnectionTimeOutException
* @param socketTimeout 指客户端从服务器读取数据的timeout,超出后会抛出SocketTimeOutException
*/
public HTTPUtils(int connectionRequestTimeout, int connectTimeout, int socketTimeout){
config = RequestConfig.custom()
.setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
} /**
* post请求
* @param url String
* @param header String
* @param requestBody String
* @return 自定义Response
*/
public Response post(String url, String header, String requestBody) throws IOException {
CloseableHttpClient httpclient = buildSSLCloseableHttpClient(url);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(config);
if (header != null && !header.equals("")) {
for (Map.Entry<String, String> entry : getRequestHeader(header).entrySet()) {
httppost.setHeader(entry.getKey(), entry.getValue());
}
}
httppost.setEntity(new StringEntity(requestBody));
CloseableHttpResponse response = httpclient.execute(httppost);
return getResponse(response);
} /**
* get请求
* @param url String
* @param header String
* @return 自定义Response
*/
public Response get(String url, String header) throws IOException {
CloseableHttpClient httpclient = buildSSLCloseableHttpClient(url);
HttpGet httpget = new HttpGet(url);
httpget.setConfig(config);
if (header != null && !header.equals("")) {
for (Map.Entry<String, String> entry : getRequestHeader(header).entrySet()) {
httpget.setHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpclient.execute(httpget);
return getResponse(response);
} /**
* header格式[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]
* @param header String
* @return Map<String, String>
*/
private Map<String, String> getRequestHeader(String header){
Map<String, String> headerMap = new HashMap<String, String>();
JSONArray headerArray = JSONArray.parseArray(header);
for (int i=0; i<headerArray.size(); i++){
JSONObject headerObject = headerArray.getJSONObject(i);
for (String key : headerObject.keySet()){
headerMap.put(key, headerObject.getString(key));
}
}
return headerMap;
} /**
* 获取response的header
* @param headers Header[]
* @return Map<String, String>
*/
private Map<String, String> getResponseHeader(Header[] headers){
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : headers) {
headerMap.put(header.getName(), header.getValue());
}
return headerMap;
} /**
* https忽略证书
* @return CloseableHttpClient
*/
private CloseableHttpClient buildSSLCloseableHttpClient(String url) {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) {
return true;
}
}).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return url.startsWith("https:") ? HttpClients.custom().setSSLSocketFactory(sslsf).build() : HttpClients.createDefault();
} /**
* 获取自定义Response
* @param response CloseableHttpResponse
* @return Response
*/
private Response getResponse(CloseableHttpResponse response){
Response res = null;
try {
String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
res = new Response();
res.setResponseCode(response.getStatusLine().getStatusCode());
res.setResponseHeader(getResponseHeader(response.getAllHeaders()));
res.setResponseBody(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
} /**
* json to xml
* @param json String
* @return
*/
public String json2xml(String json) {
org.json.JSONObject jsonObj = new org.json.JSONObject(json);
return "<xml>" + XML.toString(jsonObj) + "</xml>";
} /**
* xml to json
* @param xml String
* @return
*/
public String xml2json(String xml) {
org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
return xmlJSONObj.toString();
} @Data
public class Response{
private int responseCode;
private Map<String, String> responseHeader;
private Object responseBody;
} }

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>Httpdemo</groupId>
<artifactId>Httpdemo</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency> </dependencies> </project>

最新文章

  1. Java 单例模式详解
  2. 从2G到5G, 基站天线过去与未来
  3. CozyRSS开发记录-中断
  4. 转载:《TypeScript 中文入门教程》 11、声明合并
  5. 同步、更新、下载Android Source &amp; SDK from 国内镜像站(转载)
  6. 如何用Matlab将cell数据写入文件
  7. 前端之css、JavaScript和DOM
  8. [CLR via C#]16. 数组
  9. 出现java.lang.NoSuchFieldException resourceEntries错误的解决方法
  10. Kruscal 、 Prime Template
  11. Angular4.0学习笔记 从入门到实战打造在线竞拍网站学习笔记之二--路由
  12. JSR-303 数据校验学习
  13. sbt安裝與配置
  14. ssm注入失败
  15. 安装IDEA的历程
  16. 论文笔记:Selective Search for Object Recognition
  17. 通过zabbix自带api进行主机的批量添加操作
  18. uboot下读取flash,上传tftp服务器、下载
  19. nohup php -f xx.php &amp;
  20. 学习mysql replication

热门文章

  1. java 虚拟机内存模型
  2. final关键字总结
  3. Python——使用Pycharm连接数据库
  4. C#嵌入动态链接库到可执行文件
  5. 利用 Python_tkinter 完成 2048 游戏
  6. Awesome CLI
  7. 洛谷P4719 动态dp
  8. 【洛谷P3605】晋升者计数
  9. JSTL和EL的使用
  10. css文件引人的三种方式