RestApiUtils.java 25 KB

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