RestApiUtils.java 27 KB

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