HttpUtil.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 (org.apache.http.conn.ConnectTimeoutException cte) {
  84. log.debug(url + " 请求超时。", cte);
  85. log.info(url + " 请求超时。");
  86. } catch (Exception e) {
  87. log.info("请求 " + url + " 失败。", e);
  88. }
  89. return result;
  90. }
  91. /**
  92. * 带请求头的 get 请求
  93. *
  94. * @param closeableHttpClient http 客户端
  95. * @param requestConfig 请求配置
  96. * @param url 请求路径带参数
  97. * @param headers 请求头
  98. * @return 请求结果
  99. * @throws IOException IO异常
  100. */
  101. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url,
  102. Map<String, String> headers) throws IOException {
  103. //1 创建 post 请求
  104. HttpGet get = new HttpGet(url);
  105. //2 设置请求默认配置
  106. get.setConfig(requestConfig);
  107. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  108. if (!CollectionUtil.isEmpty(headers)) {
  109. headers.forEach(get::setHeader);
  110. }
  111. //4 发送请求
  112. CloseableHttpResponse response = closeableHttpClient.execute(get);
  113. //5 处理返回结果,
  114. //5-1 如果状态码为200,就是正常返回
  115. int statusCode = response.getStatusLine().getStatusCode();
  116. if (statusCode == 200) {
  117. return EntityUtils.toString(response.getEntity());
  118. } else {
  119. throw new RuntimeException("------- 请求错误:" + statusCode);
  120. }
  121. }
  122. /**
  123. * 默认请求头的 get 请求下载文件
  124. *
  125. * @param url 请求地址
  126. * @return 文件流
  127. * @throws IOException 异常
  128. */
  129. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) throws IOException {
  130. return getInputStream(closeableHttpClient, requestConfig, url, null);
  131. }
  132. /**
  133. * 自定义请求头的 get 请求下载文件
  134. *
  135. * @param url 请求地址
  136. * @param headers 请求头,可为 null
  137. * @return 文件流
  138. * @throws IOException 异常
  139. */
  140. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers) throws IOException {
  141. InputStream result = null;
  142. try {
  143. //1 创建 post 请求
  144. HttpGet get = new HttpGet(url);
  145. //2 设置请求默认配置
  146. get.setConfig(requestConfig);
  147. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  148. if (!CollectionUtil.isEmpty(headers)) {
  149. headers.forEach(get::setHeader);
  150. }
  151. //4 发送请求
  152. CloseableHttpResponse response = closeableHttpClient.execute(get);
  153. //5 处理返回结果,
  154. //5-1 如果状态码为200,就是正常返回
  155. int statusCode = response.getStatusLine().getStatusCode();
  156. log.info("请求 " + url + " 状态码为:" + statusCode);
  157. if (statusCode == 200) {
  158. result = response.getEntity().getContent();
  159. }
  160. } catch (Exception e) {
  161. log.info("请求 " + url + " 失败。", e);
  162. }
  163. return result;
  164. }
  165. /**
  166. * 自定义请求头的 post 请求
  167. */
  168. public static String post(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  169. //1 创建 post 请求
  170. HttpPost post = new HttpPost(url);
  171. //2 设置请求默认配置
  172. post.setConfig(requestConfig);
  173. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  174. if (!CollectionUtil.isEmpty(headers)) {
  175. headers.forEach(post::setHeader);
  176. }
  177. //4 设置请求体
  178. post.addHeader("Content-Type", "application/json");
  179. if (!CollectionUtil.isEmpty(params)) {
  180. post.setEntity(new StringEntity(JsonUtil.beanToJson(params), "utf-8"));
  181. }
  182. //5 发送请求
  183. CloseableHttpResponse response = closeableHttpClient.execute(post);
  184. //6 处理返回结果,
  185. //6-1 如果状态码为200,就是正常返回
  186. int statusCode = response.getStatusLine().getStatusCode();
  187. if (statusCode == 200) {
  188. return EntityUtils.toString(response.getEntity());
  189. } else {
  190. throw new RuntimeException("请求错误:" + statusCode);
  191. }
  192. }
  193. //
  194. // /**
  195. // * 通过 get 请求下载文件
  196. // * 发送 get 请求,get 请求的参数在 url 里
  197. // *
  198. // * @param url 请求地址
  199. // * @param headers 请求头,可为 null
  200. // * @return 文件流
  201. // * @throws IOException 异常
  202. // */
  203. // public static InputStream getDownload(String url, Map<String, String> headers) throws IOException {
  204. // //1 创建 post 请求
  205. // HttpGet get = new HttpGet(url);
  206. // //2 设置请求默认配置
  207. // get.setConfig(requestConfig);
  208. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  209. // if (!CollectionUtil.isEmpty(headers)) {
  210. // headers.forEach(get::setHeader);
  211. // }
  212. // //4 发送请求
  213. // CloseableHttpResponse response = httpClient.execute(get);
  214. // //5 处理返回结果,
  215. // //5-1 如果状态码为200,就是正常返回
  216. // int statusCode = response.getStatusLine().getStatusCode();
  217. // if (statusCode == 200) {
  218. // return response.getEntity().getContent();
  219. // } else {
  220. // throw new RuntimeException("------- 请求错误:" + statusCode);
  221. // }
  222. // }
  223. //
  224. //
  225. // /**
  226. // * 发送 post 请求
  227. // */
  228. // public static InputStream postUpload(String url) throws IOException {
  229. // //1 创建 post 请求
  230. // HttpPost post = new HttpPost(url);
  231. // //2 设置请求默认配置
  232. // post.setConfig(requestConfig);
  233. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  234. // post.setHeader("Content-type", "multipart/form-data");
  235. // //5 发送请求
  236. // CloseableHttpResponse response = httpClient.execute(post);
  237. // //6 处理返回结果,
  238. // //6-1 如果状态码为 200,就是正常返回
  239. // int statusCode = response.getStatusLine().getStatusCode();
  240. // if (statusCode == 200) {
  241. // return response.getEntity().getContent();
  242. // } else {
  243. // throw new RuntimeException("------- 请求错误:" + statusCode);
  244. // }
  245. // }
  246. //
  247. // /**
  248. // * 发送 post 请求
  249. // */
  250. // public static InputStream postDownload(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  251. // //1 创建 post 请求
  252. // HttpPost post = new HttpPost(url);
  253. // //2 设置请求默认配置
  254. // post.setConfig(requestConfig);
  255. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  256. // if (!CollectionUtil.isEmpty(headers)) {
  257. // headers.forEach(post::setHeader);
  258. // }
  259. // //4 设置请求体
  260. // if (!CollectionUtil.isEmpty(params)) {
  261. // params.forEach(post::setHeader);
  262. // }
  263. // //5 发送请求
  264. // CloseableHttpResponse response = httpClient.execute(post);
  265. // //6 处理返回结果,
  266. // //6-1 如果状态码为 200,就是正常返回
  267. // int statusCode = response.getStatusLine().getStatusCode();
  268. // if (statusCode == 200) {
  269. // return response.getEntity().getContent();
  270. // } else {
  271. // throw new RuntimeException("------- 请求错误:" + statusCode);
  272. // }
  273. // }
  274. }