RestApiUtils.java 9.3 KB

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