httpcore4.4.10, httpclient4.5.6
1 package com.test.http; 2 3 import com.alibaba.fastjson.JSONArray; 4 import com.alibaba.fastjson.JSONObject; 5 import lombok.Data; 6 import org.apache.http.Consts; 7 import org.apache.http.Header; 8 import org.apache.http.client.config.RequestConfig; 9 import org.apache.http.client.methods.CloseableHttpResponse; 10 import org.apache.http.client.methods.HttpGet; 11 import org.apache.http.client.methods.HttpPost; 12 import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 13 import org.apache.http.conn.ssl.SSLContextBuilder; 14 import org.apache.http.conn.ssl.TrustStrategy; 15 import org.apache.http.entity.StringEntity; 16 import org.apache.http.impl.client.CloseableHttpClient; 17 import org.apache.http.impl.client.HttpClients; 18 import org.apache.http.util.EntityUtils; 19 import org.json.XML; 20 21 import javax.net.ssl.SSLContext; 22 import java.io.IOException; 23 import java.security.KeyManagementException; 24 import java.security.KeyStoreException; 25 import java.security.NoSuchAlgorithmException; 26 import java.security.cert.X509Certificate; 27 import java.util.HashMap; 28 import java.util.Map; 29 30 public class HTTPUtils { 31 private static RequestConfig config; 32 33 public HTTPUtils(){ 34 config = RequestConfig.custom() 35 .setConnectionRequestTimeout(3000) 36 .setConnectTimeout(3000) 37 .setSocketTimeout(3000) 38 .build(); 39 } 40 41 /** 42 * 自定义超时时间 43 * @param connectionRequestTimeout 指从连接池获取连接的timeout 44 * @param connectTimeout 指客户端和服务器建立连接的timeout,超时后会ConnectionTimeOutException 45 * @param socketTimeout 指客户端从服务器读取数据的timeout,超出后会抛出SocketTimeOutException 46 */ 47 public HTTPUtils(int connectionRequestTimeout, int connectTimeout, int socketTimeout){ 48 config = RequestConfig.custom() 49 .setConnectionRequestTimeout(connectionRequestTimeout) 50 .setConnectTimeout(connectTimeout) 51 .setSocketTimeout(socketTimeout) 52 .build(); 53 } 54 55 /** 56 * post请求 57 * @param url String 58 * @param header String 59 * @param requestBody String 60 * @return 自定义Response 61 */ 62 public Response post(String url, String header, String requestBody) throws IOException { 63 64 CloseableHttpClient httpclient = buildSSLCloseableHttpClient(url); 65 HttpPost httppost = new HttpPost(url); 66 httppost.setConfig(config); 67 if (header != null && !header.equals("")) { 68 for (Map.Entry<String, String> entry : getRequestHeader(header).entrySet()) { 69 httppost.setHeader(entry.getKey(), entry.getValue()); 70 } 71 } 72 httppost.setEntity(new StringEntity(requestBody)); 73 CloseableHttpResponse response = httpclient.execute(httppost); 74 return getResponse(response); 75 } 76 77 /** 78 * get请求 79 * @param url String 80 * @param header String 81 * @return 自定义Response 82 */ 83 public Response get(String url, String header) throws IOException { 84 85 CloseableHttpClient httpclient = buildSSLCloseableHttpClient(url); 86 HttpGet httpget = new HttpGet(url); 87 httpget.setConfig(config); 88 if (header != null && !header.equals("")) { 89 for (Map.Entry<String, String> entry : getRequestHeader(header).entrySet()) { 90 httpget.setHeader(entry.getKey(), entry.getValue()); 91 } 92 } 93 CloseableHttpResponse response = httpclient.execute(httpget); 94 return getResponse(response); 95 } 96 97 /** 98 * header格式[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}] 99 * @param header String 100 * @return Map<String, String> 101 */ 102 private Map<String, String> getRequestHeader(String header){ 103 Map<String, String> headerMap = new HashMap<String, String>(); 104 JSONArray headerArray = JSONArray.parseArray(header); 105 for (int i=0; i<headerArray.size(); i++){ 106 JSONObject headerObject = headerArray.getJSONObject(i); 107 for (String key : headerObject.keySet()){ 108 headerMap.put(key, headerObject.getString(key)); 109 } 110 } 111 return headerMap; 112 } 113 114 /** 115 * 获取response的header 116 * @param headers Header[] 117 * @return Map<String, String> 118 */ 119 private Map<String, String> getResponseHeader(Header[] headers){ 120 Map<String, String> headerMap = new HashMap<String, String>(); 121 for (Header header : headers) { 122 headerMap.put(header.getName(), header.getValue()); 123 } 124 return headerMap; 125 } 126 127 /** 128 * https忽略证书 129 * @return CloseableHttpClient 130 */ 131 private CloseableHttpClient buildSSLCloseableHttpClient(String url) { 132 SSLContext sslContext = null; 133 try { 134 sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { 135 public boolean isTrusted(X509Certificate[] chain, String authType) { 136 return true; 137 } 138 }).build(); 139 } catch (NoSuchAlgorithmException e) { 140 e.printStackTrace(); 141 } catch (KeyManagementException e) { 142 e.printStackTrace(); 143 } catch (KeyStoreException e) { 144 e.printStackTrace(); 145 } 146 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( 147 sslContext, new String[] { "TLSv1" }, null, 148 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 149 return url.startsWith("https:") ? HttpClients.custom().setSSLSocketFactory(sslsf).build() : HttpClients.createDefault(); 150 } 151 152 /** 153 * 获取自定义Response 154 * @param response CloseableHttpResponse 155 * @return Response 156 */ 157 private Response getResponse(CloseableHttpResponse response){ 158 Response res = null; 159 try { 160 String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8); 161 res = new Response(); 162 res.setResponseCode(response.getStatusLine().getStatusCode()); 163 res.setResponseHeader(getResponseHeader(response.getAllHeaders())); 164 res.setResponseBody(result); 165 } catch (IOException e) { 166 e.printStackTrace(); 167 } finally { 168 try { 169 response.close(); 170 } catch (IOException e) { 171 e.printStackTrace(); 172 } 173 } 174 return res; 175 } 176 177 /** 178 * json to xml 179 * @param json String 180 * @return 181 */ 182 public String json2xml(String json) { 183 org.json.JSONObject jsonObj = new org.json.JSONObject(json); 184 return "<xml>" + XML.toString(jsonObj) + "</xml>"; 185 } 186 187 /** 188 * xml to json 189 * @param xml String 190 * @return 191 */ 192 public String xml2json(String xml) { 193 org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", "")); 194 return xmlJSONObj.toString(); 195 } 196 197 @Data 198 public class Response{ 199 private int responseCode; 200 private Map<String, String> responseHeader; 201 private Object responseBody; 202 } 203 204 }
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>