HttpUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package api.common.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.http.client.config.RequestConfig;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.config.Registry;
  8. import org.apache.http.config.RegistryBuilder;
  9. import org.apache.http.conn.socket.ConnectionSocketFactory;
  10. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  11. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  12. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  13. import org.apache.http.entity.StringEntity;
  14. import org.apache.http.impl.client.CloseableHttpClient;
  15. import org.apache.http.impl.client.HttpClients;
  16. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  17. import org.apache.http.ssl.SSLContextBuilder;
  18. import org.apache.http.util.EntityUtils;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.security.KeyManagementException;
  22. import java.security.KeyStoreException;
  23. import java.security.NoSuchAlgorithmException;
  24. import java.util.Map;
  25. /**
  26. * <dependency>
  27. * <groupId>org.apache.httpcomponents</groupId>
  28. * <artifactId>httpclient</artifactId>
  29. * <version>${http.client.version}</version>
  30. * </dependency>
  31. */
  32. @Slf4j
  33. public class HttpUtil {
  34. public static CloseableHttpClient getHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
  35. PlainConnectionSocketFactory plainConnectionSocketFactory = new PlainConnectionSocketFactory();
  36. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
  37. SSLContextBuilder.create().loadTrustMaterial(null, (x509Certificates, s) -> true).build(), // 全部信任 不做身份鉴定
  38. new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"},
  39. null,
  40. NoopHostnameVerifier.INSTANCE);
  41. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
  42. .register("http", plainConnectionSocketFactory)
  43. .register("https", sslConnectionSocketFactory)
  44. .build();
  45. PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
  46. pool.setMaxTotal(300);
  47. pool.setDefaultMaxPerRoute(300);
  48. return HttpClients.custom().setConnectionManager(pool).build();
  49. }
  50. public static RequestConfig getRequestConfig() {
  51. return RequestConfig.custom()
  52. .setSocketTimeout(5000)
  53. .setConnectTimeout(5000)
  54. .setConnectionRequestTimeout(5000)
  55. .setRedirectsEnabled(false)
  56. .setExpectContinueEnabled(false)
  57. .build();
  58. }
  59. /**
  60. * 默认请求头的 get 请求
  61. *
  62. * @param closeableHttpClient http 客户端
  63. * @param requestConfig 请求配置
  64. * @param url 请求路径带参数
  65. * @return 请求结果
  66. */
  67. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) {
  68. String result = null;
  69. try {
  70. //1 创建 post 请求
  71. HttpGet get = new HttpGet(url);
  72. get.setConfig(requestConfig);
  73. //2 发送请求
  74. CloseableHttpResponse response = closeableHttpClient.execute(get);
  75. //3 处理返回结果,如果状态码为200,就是正常返回
  76. int statusCode = response.getStatusLine().getStatusCode();
  77. if (statusCode == 200) {
  78. result = EntityUtils.toString(response.getEntity());
  79. } else {
  80. log.error(response.getEntity().toString());
  81. throw new RuntimeException("get() 请求错误:" + response);
  82. }
  83. } catch (Exception e) {
  84. log.info("请求 " + url + " 失败。", e);
  85. }
  86. return result;
  87. }
  88. /**
  89. * 带请求头的 get 请求
  90. *
  91. * @param closeableHttpClient http 客户端
  92. * @param requestConfig 请求配置
  93. * @param url 请求路径带参数
  94. * @param headers 请求头
  95. * @return 请求结果
  96. * @throws IOException IO异常
  97. */
  98. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url,
  99. Map<String, String> headers) throws IOException {
  100. //1 创建 post 请求
  101. HttpGet get = new HttpGet(url);
  102. //2 设置请求默认配置
  103. get.setConfig(requestConfig);
  104. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  105. if (!CollectionUtil.isEmpty(headers)) {
  106. headers.forEach(get::setHeader);
  107. }
  108. //4 发送请求
  109. CloseableHttpResponse response = closeableHttpClient.execute(get);
  110. //5 处理返回结果,
  111. //5-1 如果状态码为200,就是正常返回
  112. int statusCode = response.getStatusLine().getStatusCode();
  113. if (statusCode == 200) {
  114. return EntityUtils.toString(response.getEntity());
  115. } else {
  116. throw new RuntimeException("------- 请求错误:" + statusCode);
  117. }
  118. }
  119. /**
  120. * 默认请求头的 get 请求下载文件
  121. *
  122. * @param url 请求地址
  123. * @return 文件流
  124. * @throws IOException 异常
  125. */
  126. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) throws IOException {
  127. return getInputStream(closeableHttpClient, requestConfig, url, null);
  128. }
  129. /**
  130. * 自定义请求头的 get 请求下载文件
  131. *
  132. * @param url 请求地址
  133. * @param headers 请求头,可为 null
  134. * @return 文件流
  135. * @throws IOException 异常
  136. */
  137. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers) throws IOException {
  138. InputStream result = null;
  139. try {
  140. //1 创建 post 请求
  141. HttpGet get = new HttpGet(url);
  142. //2 设置请求默认配置
  143. get.setConfig(requestConfig);
  144. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  145. if (!CollectionUtil.isEmpty(headers)) {
  146. headers.forEach(get::setHeader);
  147. }
  148. //4 发送请求
  149. CloseableHttpResponse response = closeableHttpClient.execute(get);
  150. //5 处理返回结果,
  151. //5-1 如果状态码为200,就是正常返回
  152. int statusCode = response.getStatusLine().getStatusCode();
  153. log.info("请求 " + url + " 状态码为:" + statusCode);
  154. if (statusCode == 200) {
  155. result = response.getEntity().getContent();
  156. }
  157. } catch (Exception e) {
  158. log.info("请求 " + url + " 失败。", e);
  159. }
  160. return result;
  161. }
  162. /**
  163. * 自定义请求头的 post 请求
  164. */
  165. public static String post(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  166. //1 创建 post 请求
  167. HttpPost post = new HttpPost(url);
  168. //2 设置请求默认配置
  169. post.setConfig(requestConfig);
  170. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  171. if (!CollectionUtil.isEmpty(headers)) {
  172. headers.forEach(post::setHeader);
  173. }
  174. //4 设置请求体
  175. post.addHeader("Content-Type", "application/json");
  176. if (!CollectionUtil.isEmpty(params)) {
  177. post.setEntity(new StringEntity(JsonUtil.beanToJson(params), "utf-8"));
  178. }
  179. //5 发送请求
  180. CloseableHttpResponse response = closeableHttpClient.execute(post);
  181. //6 处理返回结果,
  182. //6-1 如果状态码为200,就是正常返回
  183. int statusCode = response.getStatusLine().getStatusCode();
  184. if (statusCode == 200) {
  185. return EntityUtils.toString(response.getEntity());
  186. } else {
  187. throw new RuntimeException("请求错误:" + statusCode);
  188. }
  189. }
  190. //
  191. // /**
  192. // * 通过 get 请求下载文件
  193. // * 发送 get 请求,get 请求的参数在 url 里
  194. // *
  195. // * @param url 请求地址
  196. // * @param headers 请求头,可为 null
  197. // * @return 文件流
  198. // * @throws IOException 异常
  199. // */
  200. // public static InputStream getDownload(String url, Map<String, String> headers) throws IOException {
  201. // //1 创建 post 请求
  202. // HttpGet get = new HttpGet(url);
  203. // //2 设置请求默认配置
  204. // get.setConfig(requestConfig);
  205. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  206. // if (!CollectionUtil.isEmpty(headers)) {
  207. // headers.forEach(get::setHeader);
  208. // }
  209. // //4 发送请求
  210. // CloseableHttpResponse response = httpClient.execute(get);
  211. // //5 处理返回结果,
  212. // //5-1 如果状态码为200,就是正常返回
  213. // int statusCode = response.getStatusLine().getStatusCode();
  214. // if (statusCode == 200) {
  215. // return response.getEntity().getContent();
  216. // } else {
  217. // throw new RuntimeException("------- 请求错误:" + statusCode);
  218. // }
  219. // }
  220. //
  221. //
  222. // /**
  223. // * 发送 post 请求
  224. // */
  225. // public static InputStream postUpload(String url) throws IOException {
  226. // //1 创建 post 请求
  227. // HttpPost post = new HttpPost(url);
  228. // //2 设置请求默认配置
  229. // post.setConfig(requestConfig);
  230. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  231. // post.setHeader("Content-type", "multipart/form-data");
  232. // //5 发送请求
  233. // CloseableHttpResponse response = httpClient.execute(post);
  234. // //6 处理返回结果,
  235. // //6-1 如果状态码为 200,就是正常返回
  236. // int statusCode = response.getStatusLine().getStatusCode();
  237. // if (statusCode == 200) {
  238. // return response.getEntity().getContent();
  239. // } else {
  240. // throw new RuntimeException("------- 请求错误:" + statusCode);
  241. // }
  242. // }
  243. //
  244. // /**
  245. // * 发送 post 请求
  246. // */
  247. // public static InputStream postDownload(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  248. // //1 创建 post 请求
  249. // HttpPost post = new HttpPost(url);
  250. // //2 设置请求默认配置
  251. // post.setConfig(requestConfig);
  252. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  253. // if (!CollectionUtil.isEmpty(headers)) {
  254. // headers.forEach(post::setHeader);
  255. // }
  256. // //4 设置请求体
  257. // if (!CollectionUtil.isEmpty(params)) {
  258. // params.forEach(post::setHeader);
  259. // }
  260. // //5 发送请求
  261. // CloseableHttpResponse response = httpClient.execute(post);
  262. // //6 处理返回结果,
  263. // //6-1 如果状态码为 200,就是正常返回
  264. // int statusCode = response.getStatusLine().getStatusCode();
  265. // if (statusCode == 200) {
  266. // return response.getEntity().getContent();
  267. // } else {
  268. // throw new RuntimeException("------- 请求错误:" + statusCode);
  269. // }
  270. // }
  271. }