RestApiUtils.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package com.yiidata.intergration.api.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.HttpClient;
  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.config.Registry;
  13. import org.apache.http.config.RegistryBuilder;
  14. import org.apache.http.config.SocketConfig;
  15. import org.apache.http.conn.socket.ConnectionSocketFactory;
  16. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  17. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  18. import org.apache.http.entity.StringEntity;
  19. import org.apache.http.impl.client.CloseableHttpClient;
  20. import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
  21. import org.apache.http.impl.client.HttpClients;
  22. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  23. import org.apache.http.params.BasicHttpParams;
  24. import org.apache.http.util.EntityUtils;
  25. import org.slf4j.Logger;
  26. import org.slf4j.LoggerFactory;
  27. import javax.net.ssl.SSLContext;
  28. import javax.net.ssl.TrustManager;
  29. import javax.net.ssl.X509TrustManager;
  30. import java.io.IOException;
  31. import java.security.KeyManagementException;
  32. import java.security.NoSuchAlgorithmException;
  33. import java.security.cert.CertificateException;
  34. import java.util.HashMap;
  35. import java.util.Map;
  36. /**
  37. *
  38. * 封装 RestApi 调用
  39. *
  40. *
  41. * <pre>
  42. *
  43. * Created by zhaopx.
  44. * User: zhaopx
  45. * Date: 2020/4/3
  46. * Time: 17:38
  47. *
  48. * </pre>
  49. *
  50. * @author zhaopx
  51. */
  52. public class RestApiUtils {
  53. static Logger log = LoggerFactory.getLogger(RestApiUtils.class);
  54. /**
  55. * http client
  56. */
  57. static final CloseableHttpClient httpClient;
  58. static {
  59. try {
  60. //设置协议http和https对应的处理socket链接工厂的对象
  61. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  62. .register("http", PlainConnectionSocketFactory.INSTANCE)
  63. .register("https", new SSLConnectionSocketFactory(createIgnoreVerifySSL()))
  64. .build();
  65. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  66. httpClient = HttpClients.custom()
  67. .setConnectionManager(cm)
  68. .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(180000).build())
  69. .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
  70. .build();
  71. } catch (Exception e) {
  72. throw new IllegalStateException(e);
  73. }
  74. }
  75. /**
  76. * 绕过验证
  77. *
  78. * @return
  79. * @throws NoSuchAlgorithmException
  80. * @throws KeyManagementException
  81. */
  82. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  83. SSLContext sc = SSLContext.getInstance("SSLv3");
  84. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  85. X509TrustManager trustManager = new X509TrustManager() {
  86. @Override
  87. public void checkClientTrusted(
  88. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  89. String paramString) throws CertificateException {
  90. }
  91. @Override
  92. public void checkServerTrusted(
  93. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  94. String paramString) throws CertificateException {
  95. }
  96. @Override
  97. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  98. return null;
  99. }
  100. };
  101. sc.init(null, new TrustManager[] { trustManager }, null);
  102. return sc;
  103. }
  104. /**
  105. * 调用一次远程 api
  106. * @param url
  107. * @return
  108. * @throws IOException
  109. */
  110. public static Map<String, Object> post(String url) throws IOException {
  111. return post(url, new HashMap<>(), false);
  112. }
  113. /**
  114. * 调用一次远程 api
  115. * @param url
  116. * @return
  117. * @throws IOException
  118. */
  119. public static Map<String, Object> post(String url, boolean not200ThrowError) throws IOException {
  120. return post(url, new HashMap<>(), not200ThrowError);
  121. }
  122. /**
  123. * 通过 Post 请求调用Rest 接口
  124. *
  125. * @param url
  126. * @param json
  127. * @return
  128. * @throws IOException
  129. */
  130. public static Map<String, Object> post(String url, Map<String, Object> json) throws IOException {
  131. return post(url, json, false);
  132. }
  133. /**
  134. * 通过 Post 请求调用Rest 接口
  135. * @param url
  136. * @param json
  137. * @param not200ThrowError 为 true 时,当返回不是 200,则抛出异常
  138. * @return
  139. * @throws IOException
  140. */
  141. public static Map<String, Object> post(String url, Map<String, Object> json, boolean not200ThrowError) throws IOException {
  142. return post(url, JSON.toJSONString(json), not200ThrowError);
  143. }
  144. public static Map<String, Object> post(String url, String jsonStr, boolean not200ThrowError) throws IOException {
  145. HttpPost post = new HttpPost(url);
  146. StringEntity entity = new StringEntity(jsonStr, "UTF-8");
  147. entity.setContentType("application/json");
  148. post.setEntity(entity);
  149. CloseableHttpResponse resp = null;
  150. try {
  151. resp = httpClient.execute(post);
  152. log.info("execute url {} return code: {}", url, resp.getStatusLine().getStatusCode());
  153. HttpEntity entity1 = resp.getEntity();
  154. String result = EntityUtils.toString(entity1);
  155. EntityUtils.consume(entity1);
  156. if(not200ThrowError && resp.getStatusLine().getStatusCode() != 200) {
  157. throw new IOException(result);
  158. }
  159. Object jsonResult = JSON.parse(result);
  160. JSONObject jsonObject = new JSONObject(2);
  161. if(jsonResult instanceof JSONArray) {
  162. jsonObject.put("result", jsonResult);
  163. } else {
  164. jsonObject = (JSONObject) jsonResult;
  165. }
  166. jsonObject.put("status_code", resp.getStatusLine().getStatusCode());
  167. return jsonObject;
  168. } finally {
  169. if(resp != null) {
  170. resp.close();
  171. }
  172. }
  173. }
  174. //---------
  175. /**
  176. * 调用一次远程 api
  177. * @param url
  178. * @return
  179. * @throws IOException
  180. */
  181. public static Map<String, Object> get(String url) throws IOException {
  182. return get(url, new HashMap<>(), false);
  183. }
  184. /**
  185. * 调用一次远程 api
  186. * @param url
  187. * @return
  188. * @throws IOException
  189. */
  190. public static Map<String, Object> get(String url, boolean not200ThrowError) throws IOException {
  191. return get(url, new HashMap<>(), not200ThrowError);
  192. }
  193. /**
  194. * 通过 Post 请求调用Rest 接口
  195. *
  196. * @param url
  197. * @param json
  198. * @return
  199. * @throws IOException
  200. */
  201. public static Map<String, Object> get(String url, Map<String, Object> json) throws IOException {
  202. return get(url, json, false);
  203. }
  204. /**
  205. * 通过 Post 请求调用Rest 接口
  206. * @param url
  207. * @param json
  208. * @param not200ThrowError 为 true 时,当返回不是 200,则抛出异常
  209. * @return
  210. * @throws IOException
  211. */
  212. public static Map<String, Object> get(String url, Map<String, Object> json, boolean not200ThrowError) throws IOException {
  213. HttpGet get = new HttpGet(url);
  214. if(json != null && !json.isEmpty()) {
  215. BasicHttpParams params = new BasicHttpParams();
  216. for (Map.Entry<String, Object> entry : json.entrySet()) {
  217. params.setParameter(entry.getKey(), entry.getValue());
  218. }
  219. get.setParams(params);
  220. }
  221. CloseableHttpResponse resp = null;
  222. try {
  223. resp = httpClient.execute(get);
  224. log.info("execute url {} return code: {}", url, resp.getStatusLine().getStatusCode());
  225. HttpEntity entity = resp.getEntity();
  226. String result = EntityUtils.toString(entity);
  227. EntityUtils.consume(entity);
  228. if(not200ThrowError && resp.getStatusLine().getStatusCode() != 200) {
  229. throw new IOException(result);
  230. }
  231. Object jsonResult = JSON.parse(result);
  232. JSONObject jsonObject = new JSONObject(2);
  233. if(jsonResult instanceof JSONArray) {
  234. jsonObject.put("result", jsonResult);
  235. } else {
  236. jsonObject = (JSONObject) jsonResult;
  237. }
  238. jsonObject.put("status_code", resp.getStatusLine().getStatusCode());
  239. return jsonObject;
  240. } finally {
  241. if(resp != null) {
  242. resp.close();
  243. }
  244. }
  245. }
  246. /**
  247. * 关闭 RPC 调用
  248. * @throws IOException
  249. */
  250. public void shutdown() throws IOException {
  251. httpClient.close();
  252. }
  253. }