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>
05-08 08:08