RestApiUtils.java 8.5 KB

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