RestApiUtils.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 com.google.common.io.ByteStreams;
  6. import com.google.common.net.HttpHeaders;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.apache.http.Header;
  10. import org.apache.http.HeaderElement;
  11. import org.apache.http.HttpEntity;
  12. import org.apache.http.HttpResponse;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.config.RequestConfig;
  16. import org.apache.http.client.methods.CloseableHttpResponse;
  17. import org.apache.http.client.methods.HttpGet;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.config.Registry;
  20. import org.apache.http.config.RegistryBuilder;
  21. import org.apache.http.config.SocketConfig;
  22. import org.apache.http.conn.socket.ConnectionSocketFactory;
  23. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  24. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  25. import org.apache.http.entity.StringEntity;
  26. import org.apache.http.entity.mime.MultipartEntityBuilder;
  27. import org.apache.http.impl.client.BasicCookieStore;
  28. import org.apache.http.impl.client.CloseableHttpClient;
  29. import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
  30. import org.apache.http.impl.client.HttpClients;
  31. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  32. import org.apache.http.params.BasicHttpParams;
  33. import org.apache.http.util.EntityUtils;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import javax.net.ssl.SSLContext;
  37. import javax.net.ssl.TrustManager;
  38. import javax.net.ssl.X509TrustManager;
  39. import java.io.File;
  40. import java.io.FileNotFoundException;
  41. import java.io.FileOutputStream;
  42. import java.io.IOException;
  43. import java.io.InputStream;
  44. import java.io.OutputStream;
  45. import java.net.URLDecoder;
  46. import java.nio.charset.StandardCharsets;
  47. import java.nio.file.Paths;
  48. import java.security.KeyManagementException;
  49. import java.security.NoSuchAlgorithmException;
  50. import java.security.cert.CertificateException;
  51. import java.util.HashMap;
  52. import java.util.Map;
  53. /**
  54. *
  55. * 封装 RestApi 调用
  56. *
  57. *
  58. * <pre>
  59. *
  60. * Created by zhaopx.
  61. * User: zhaopx
  62. * Date: 2020/4/3
  63. * Time: 17:38
  64. *
  65. * </pre>
  66. *
  67. * @author zhaopx
  68. */
  69. public class RestApiUtils {
  70. static Logger log = LoggerFactory.getLogger(RestApiUtils.class);
  71. /**
  72. * http client
  73. */
  74. static final CloseableHttpClient httpClient;
  75. /**
  76. * Cookie store
  77. */
  78. private final static BasicCookieStore cookieStore = new BasicCookieStore();
  79. static {
  80. try {
  81. //设置协议http和https对应的处理socket链接工厂的对象
  82. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  83. .register("http", PlainConnectionSocketFactory.INSTANCE)
  84. .register("https", new SSLConnectionSocketFactory(createIgnoreVerifySSL()))
  85. .build();
  86. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  87. httpClient = HttpClients.custom()
  88. .setConnectionManager(cm)
  89. .setDefaultCookieStore(cookieStore)
  90. .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(180000).build())
  91. .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
  92. .build();
  93. } catch (Exception e) {
  94. throw new IllegalStateException(e);
  95. }
  96. }
  97. /**
  98. * 绕过验证
  99. *
  100. * @return
  101. * @throws NoSuchAlgorithmException
  102. * @throws KeyManagementException
  103. */
  104. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  105. SSLContext sc = SSLContext.getInstance("SSLv3");
  106. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  107. X509TrustManager trustManager = new X509TrustManager() {
  108. @Override
  109. public void checkClientTrusted(
  110. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  111. String paramString) throws CertificateException {
  112. }
  113. @Override
  114. public void checkServerTrusted(
  115. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  116. String paramString) throws CertificateException {
  117. }
  118. @Override
  119. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  120. return null;
  121. }
  122. };
  123. sc.init(null, new TrustManager[] { trustManager }, null);
  124. return sc;
  125. }
  126. /**
  127. * 调用一次远程 api
  128. * @param url
  129. * @return
  130. * @throws IOException
  131. */
  132. public static Map<String, Object> post(String url) throws IOException {
  133. return post(url, new HashMap<>(), false);
  134. }
  135. /**
  136. * 调用一次远程 api
  137. * @param url
  138. * @return
  139. * @throws IOException
  140. */
  141. public static Map<String, Object> post(String url, boolean not200ThrowError) throws IOException {
  142. return post(url, new HashMap<>(), not200ThrowError);
  143. }
  144. /**
  145. * 通过 Post 请求调用Rest 接口
  146. *
  147. * @param url
  148. * @param json
  149. * @return
  150. * @throws IOException
  151. */
  152. public static Map<String, Object> post(String url, Map<String, Object> json) throws IOException {
  153. return post(url, json, false);
  154. }
  155. /**
  156. * 通过 Post 请求调用Rest 接口
  157. * @param url
  158. * @param json
  159. * @param not200ThrowError 为 true 时,当返回不是 200,则抛出异常
  160. * @return
  161. * @throws IOException
  162. */
  163. public static Map<String, Object> post(String url, Map<String, Object> json, boolean not200ThrowError) throws IOException {
  164. return post(url, JSON.toJSONString(json), not200ThrowError);
  165. }
  166. /**
  167. * POST 请求,执行远程
  168. * @param url
  169. * @param jsonStr
  170. * @param not200ThrowError
  171. * @return
  172. * @throws IOException
  173. */
  174. public static Map<String, Object> post(String url, String jsonStr, boolean not200ThrowError) throws IOException {
  175. return post(url, jsonStr, new HashMap<>(), not200ThrowError);
  176. }
  177. /**
  178. * POST 请求执行远程链接
  179. * @param url
  180. * @param jsonStr 请求 Body 体
  181. * @param header 请求头
  182. * @param not200ThrowError
  183. * @return
  184. * @throws IOException
  185. */
  186. public static Map<String, Object> post(String url, String jsonStr, Map<String, String> header, boolean not200ThrowError) throws IOException {
  187. HttpPost post = new HttpPost(url);
  188. StringEntity entity = new StringEntity(jsonStr, "UTF-8");
  189. entity.setContentType("application/json");
  190. post.setEntity(entity);
  191. if(header != null && !header.isEmpty()) {
  192. for (Map.Entry<String, String> entry : header.entrySet()) {
  193. post.addHeader(entry.getKey(), entry.getValue());
  194. }
  195. }
  196. CloseableHttpResponse resp = null;
  197. try {
  198. resp = httpClient.execute(post);
  199. log.info("execute[post] url {} return code: {}", url, resp.getStatusLine().getStatusCode());
  200. HttpEntity entity1 = resp.getEntity();
  201. String result = EntityUtils.toString(entity1);
  202. EntityUtils.consume(entity1);
  203. if(not200ThrowError && resp.getStatusLine().getStatusCode() != 200) {
  204. throw new IOException(result);
  205. }
  206. Object jsonResult = JSON.parse(result);
  207. JSONObject jsonObject = new JSONObject(2);
  208. if(jsonResult instanceof JSONArray) {
  209. jsonObject.put("result", jsonResult);
  210. } else {
  211. jsonObject = (JSONObject) jsonResult;
  212. }
  213. jsonObject.put("status_code", resp.getStatusLine().getStatusCode());
  214. return jsonObject;
  215. } finally {
  216. if(resp != null) {
  217. resp.close();
  218. }
  219. }
  220. }
  221. //---------
  222. /**
  223. * 调用一次远程 api
  224. * @param url
  225. * @return
  226. * @throws IOException
  227. */
  228. public static Map<String, Object> get(String url) throws IOException {
  229. return get(url, new HashMap<>(), false);
  230. }
  231. /**
  232. * 调用一次远程 api
  233. * @param url
  234. * @return
  235. * @throws IOException
  236. */
  237. public static Map<String, Object> get(String url, boolean not200ThrowError) throws IOException {
  238. return get(url, new HashMap<>(), not200ThrowError);
  239. }
  240. /**
  241. * 通过 Post 请求调用Rest 接口
  242. *
  243. * @param url
  244. * @param json
  245. * @return
  246. * @throws IOException
  247. */
  248. public static Map<String, Object> get(String url, Map<String, Object> json) throws IOException {
  249. return get(url, json, false);
  250. }
  251. /**
  252. * 通过 Post 请求调用Rest 接口
  253. * @param url
  254. * @param json
  255. * @param not200ThrowError 为 true 时,当返回不是 200,则抛出异常
  256. * @return
  257. * @throws IOException
  258. */
  259. public static Map<String, Object> get(String url, Map<String, Object> json, boolean not200ThrowError) throws IOException {
  260. return get(url, json, new HashMap<>(), not200ThrowError);
  261. }
  262. /**
  263. * 通过 Post 请求调用Rest 接口
  264. * @param url
  265. * @param json
  266. * @param not200ThrowError 为 true 时,当返回不是 200,则抛出异常
  267. * @return
  268. * @throws IOException
  269. */
  270. public static Map<String, Object> get(String url, Map<String, Object> json, Map<String, String> header, boolean not200ThrowError) throws IOException {
  271. HttpGet get = new HttpGet(url);
  272. if(json != null && !json.isEmpty()) {
  273. BasicHttpParams params = new BasicHttpParams();
  274. for (Map.Entry<String, Object> entry : json.entrySet()) {
  275. params.setParameter(entry.getKey(), entry.getValue());
  276. }
  277. get.setParams(params);
  278. }
  279. if(header != null && !header.isEmpty()) {
  280. for (Map.Entry<String, String> entry : header.entrySet()) {
  281. get.addHeader(entry.getKey(), entry.getValue());
  282. }
  283. }
  284. CloseableHttpResponse resp = null;
  285. try {
  286. resp = httpClient.execute(get);
  287. log.info("execute[get] url {} return code: {}", url, resp.getStatusLine().getStatusCode());
  288. HttpEntity entity = resp.getEntity();
  289. String result = EntityUtils.toString(entity);
  290. EntityUtils.consume(entity);
  291. if(not200ThrowError && resp.getStatusLine().getStatusCode() != 200) {
  292. throw new IOException(result);
  293. }
  294. Object jsonResult = JSON.parse(result);
  295. JSONObject jsonObject = new JSONObject(2);
  296. if(jsonResult instanceof JSONArray) {
  297. jsonObject.put("result", jsonResult);
  298. } else {
  299. jsonObject = (JSONObject) jsonResult;
  300. }
  301. jsonObject.put("status_code", resp.getStatusLine().getStatusCode());
  302. return jsonObject;
  303. } finally {
  304. if(resp != null) {
  305. resp.close();
  306. }
  307. }
  308. }
  309. /**
  310. * 根据url下载文件,保存到filepath中
  311. *
  312. * @param url
  313. * @param downloadDir
  314. * @return 返回 下载的文件路径
  315. */
  316. public static String download(String url, File downloadDir) throws IOException {
  317. return download(url, new HashMap<>(), downloadDir);
  318. }
  319. /**
  320. * 根据url下载文件,保存到filepath中
  321. *
  322. * @param url
  323. * @param downloadDir
  324. * @return 返回 下载的文件路径
  325. */
  326. public static String download(String url, Map<String, String> headers, File downloadDir) throws IOException {
  327. if(!downloadDir.exists()) {
  328. if(!downloadDir.mkdirs()) {
  329. throw new IOException(downloadDir.getAbsolutePath() + " not exists, do can not mkdir.");
  330. }
  331. }
  332. // 构造 Header,并且绑定,下载时登录,其实只要绑定 SessionID 就可以了
  333. HttpGet httpget = new HttpGet(url);
  334. if(headers != null) {
  335. for (Map.Entry<String, String> entry : headers.entrySet()) {
  336. httpget.setHeader(entry.getKey(), entry.getValue());
  337. }
  338. }
  339. // 开始下载
  340. HttpResponse response = httpClient.execute(httpget);
  341. String fileName = null;
  342. final Header contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
  343. if(StringUtils.contains(contentType.getValue(), "application/octet-stream") ||
  344. StringUtils.contains(contentType.getValue(), "application/force-download")) {
  345. // 下载文件
  346. fileName = getFileName(response);
  347. if(StringUtils.isBlank(fileName)) {
  348. log.warn(response.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION) + " can 'not found filename.");
  349. }
  350. }
  351. if(StringUtils.isBlank(fileName)) {
  352. fileName = getFileName(response);
  353. }
  354. if(StringUtils.isBlank(fileName)) {
  355. //无法从 header中获得文件名,如果路径是 /path/for/bar.zip 以 bar.zip 为文件名
  356. final String rawPath = httpget.getURI().getRawPath();
  357. if(!rawPath.endsWith("/")) {
  358. fileName = Paths.get(rawPath).getFileName().toString();
  359. }
  360. if(StringUtils.isBlank(fileName)) {
  361. log.warn("can not found download filename, use system timestamp.");
  362. fileName = String.valueOf(System.currentTimeMillis());
  363. }
  364. }
  365. log.info("download filename: {}", fileName);
  366. HttpEntity entity = response.getEntity();
  367. File filepath = new File(downloadDir, fileName);
  368. try(InputStream is = entity.getContent(); FileOutputStream fileout = new FileOutputStream(filepath);) {
  369. ByteStreams.copy(is, fileout);
  370. fileout.flush();
  371. }
  372. return filepath.getAbsolutePath();
  373. }
  374. /**
  375. * 获取response header中Content-Disposition中的filename值
  376. *
  377. * @param response
  378. * @return
  379. */
  380. private static String getFileName(HttpResponse response) {
  381. Header contentHeader = response.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION);
  382. String filename = null;
  383. if (contentHeader != null) {
  384. HeaderElement[] values = contentHeader.getElements();
  385. if (values.length >= 1) {
  386. NameValuePair param = values[0].getParameterByName("filename");
  387. if (param != null) {
  388. try {
  389. if(param.getValue() != null && param.getValue().contains("%")) {
  390. //filename = new String(param.getValue().toString().getBytes(), "utf-8");
  391. filename = URLDecoder.decode(param.getValue(), "UTF-8");
  392. } else {
  393. filename = param.getValue();
  394. }
  395. } catch (Exception e) {
  396. filename = param.getValue();
  397. }
  398. }
  399. }
  400. }
  401. return filename;
  402. }
  403. /**
  404. * 根据url上传文件
  405. *
  406. * @param url
  407. * @param uploadFile
  408. * @return 返回 下载的文件路径
  409. */
  410. public static Map<String, Object> upload(String url,
  411. File uploadFile) throws IOException {
  412. return upload(url, null, null, uploadFile, true);
  413. }
  414. /**
  415. * 根据url上传文件
  416. *
  417. * @param url
  418. * @param uploadFile
  419. * @return 返回 下载的文件路径
  420. */
  421. public static Map<String, Object> upload(String url,
  422. Map<String, Object> json,
  423. File uploadFile) throws IOException {
  424. return upload(url, json, null, uploadFile, true);
  425. }
  426. /**
  427. * 根据url上传文件
  428. *
  429. * @param url
  430. * @param uploadFile
  431. * @return 返回 下载的文件路径
  432. */
  433. public static Map<String, Object> upload(String url,
  434. Map<String, Object> json,
  435. Map<String, String> headers,
  436. File uploadFile) throws IOException {
  437. return upload(url, json, headers, uploadFile, true);
  438. }
  439. /**
  440. * 根据url上传文件
  441. *
  442. * @param url
  443. * @param uploadFile
  444. * @return 返回 下载的文件路径
  445. */
  446. public static Map<String, Object> upload(String url,
  447. Map<String, Object> json,
  448. Map<String, String> headers,
  449. File uploadFile,
  450. boolean not200ThrowError) throws IOException {
  451. // 文件夹 或者 是 文件不存在
  452. if(!uploadFile.exists()) {
  453. throw new FileNotFoundException(uploadFile.getAbsolutePath() + " can not found!");
  454. }
  455. if(uploadFile.isDirectory()) {
  456. throw new IllegalStateException("upload payload must be file, but found directory.");
  457. }
  458. HttpPost httpPost = new HttpPost(url);
  459. RequestConfig requestConfig = RequestConfig.custom()
  460. .setConnectTimeout(30000) // 服务器端链接超时设置 30s
  461. .setSocketTimeout(10 * 60 * 1000) // 上传等待 10 分钟
  462. .build();
  463. httpPost.setConfig(requestConfig);
  464. if(headers != null) {
  465. for (Map.Entry<String, String> entry : headers.entrySet()) {
  466. httpPost.setHeader(entry.getKey(), entry.getValue());
  467. }
  468. }
  469. MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
  470. multipartEntityBuilder.setCharset(StandardCharsets.UTF_8);
  471. //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
  472. //当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
  473. //multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
  474. multipartEntityBuilder.addBinaryBody("file", uploadFile);
  475. if(json != null) {
  476. for (Map.Entry<String, Object> entry : json.entrySet()) {
  477. multipartEntityBuilder.addTextBody(entry.getKey(), (String) entry.getValue());
  478. }
  479. }
  480. HttpEntity httpEntity = multipartEntityBuilder.build();
  481. httpPost.setEntity(httpEntity);
  482. CloseableHttpResponse httpResponse = null;
  483. try {
  484. httpResponse = httpClient.execute(httpPost);
  485. HttpEntity responseEntity = httpResponse.getEntity();
  486. int statusCode = httpResponse.getStatusLine().getStatusCode();
  487. String result = EntityUtils.toString(responseEntity);
  488. EntityUtils.consume(responseEntity);
  489. if (not200ThrowError && httpResponse.getStatusLine().getStatusCode() != 200) {
  490. throw new IOException(result);
  491. }
  492. Object jsonResult = JSON.parse(result);
  493. JSONObject jsonObject = new JSONObject(2);
  494. if (jsonResult instanceof JSONArray) {
  495. jsonObject.put("result", jsonResult);
  496. } else {
  497. jsonObject = (JSONObject) jsonResult;
  498. }
  499. jsonObject.put("status_code", statusCode);
  500. return jsonObject;
  501. } finally {
  502. if(httpResponse != null) {
  503. httpResponse.close();
  504. }
  505. }
  506. }
  507. /**
  508. * 关闭 RPC 调用
  509. * @throws IOException
  510. */
  511. public static void shutdown() throws IOException {
  512. httpClient.close();
  513. }
  514. }