Helper.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package com.kingdee.eas.custom.webbeisen.utils;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONException;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.kingdee.bos.BOSException;
  6. import com.kingdee.bos.Context;
  7. import com.kingdee.eas.common.EASBizException;
  8. import com.kingdee.eas.custom.interfacelog.businessoperationlog.*;
  9. import com.kingdee.eas.custom.interfacelog.enumdata.RequestStatusEnum;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.client.ClientProtocolException;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.client.methods.HttpPut;
  16. import org.apache.http.client.utils.URIBuilder;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.CloseableHttpClient;
  19. import org.apache.http.impl.client.HttpClients;
  20. import org.apache.http.message.BasicNameValuePair;
  21. import org.apache.http.util.EntityUtils;
  22. import java.io.ByteArrayOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.net.*;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Map.Entry;
  30. import java.util.Set;
  31. /**
  32. * 提供一些常用的HTTP请求和文件下载的辅助方法。
  33. */
  34. public class Helper {
  35. // 上下文对象,用于与Kingdee BOS系统交互
  36. public Context context;
  37. /**
  38. * 构造函数,初始化上下文对象
  39. *
  40. * @param context 上下文对象
  41. */
  42. public Helper(Context context) {
  43. this.context = context;
  44. }
  45. /**
  46. * 发送HTTP请求并返回JSON格式的响应,同时记录操作日志
  47. *
  48. * @param url 请求的URL地址
  49. * @param header 请求头信息,键值对形式
  50. * @param requestBody 请求体,以JSONObject形式表示
  51. * @param method 请求方法,支持"GET"、"POST"、"PUT"
  52. * @param businessId 业务ID
  53. * @param operate 操作名称
  54. * @param businessName 业务名称
  55. * @return 服务器返回的JSON对象
  56. * @throws URISyntaxException 如果URL格式不正确
  57. * @throws JSONException 如果JSON解析错误
  58. * @throws IOException 如果发生I/O错误
  59. * @throws ClientProtocolException 如果HTTP协议错误
  60. */
  61. public JSONObject getURL(String url, Map<String, String> header, JSONObject requestBody, String method,
  62. String businessId, String operate, String businessName)
  63. throws URISyntaxException, JSONException, ClientProtocolException, IOException {
  64. // 根据业务ID和业务名称获取操作日志信息
  65. businessId = URLDecoder.decode("businessId","UTF-8");
  66. OperateLogInfo operateLogInfo = getOperateLogInfoByBusinessId(businessId, businessName);
  67. // 获取操作日志的条目集合
  68. OperateLogEntryCollection entrys = operateLogInfo.getEntrys();
  69. // 如果条目集合为空,则初始化一个新的集合
  70. if (entrys == null) {
  71. entrys = new OperateLogEntryCollection();
  72. }
  73. // 创建一个新的操作日志条目
  74. OperateLogEntryInfo operateLogEntryInfo = new OperateLogEntryInfo();
  75. // 设置请求的URL
  76. operateLogEntryInfo.setUrl(url);
  77. // 将请求体转换为字符串
  78. String requestBodyString = requestBody.toString();
  79. // 如果请求体字符串长度超过1500,则截取前1500个字符
  80. if (requestBodyString.length() > 1500) {
  81. requestBodyString = requestBodyString.substring(0, 1500);
  82. }
  83. // 设置请求体到操作日志条目
  84. operateLogEntryInfo.setRequestBody(requestBodyString);
  85. // 将请求头信息转换为JSON字符串
  86. String jsonString = JSONObject.toJSONString(header);
  87. // 如果请求头JSON字符串长度超过1500,则截取前1500个字符
  88. if (jsonString.length() > 1500) {
  89. jsonString = jsonString.substring(0, 1500);
  90. }
  91. // 设置请求头到操作日志条目
  92. operateLogEntryInfo.setHeaded(jsonString);
  93. // 设置操作名称到操作日志条目
  94. operateLogEntryInfo.setOperate(operate);
  95. // 设置请求方法到操作日志条目
  96. operateLogEntryInfo.setMethod(method);
  97. // 用于存储服务器返回的JSON对象
  98. JSONObject responseJson = new JSONObject();
  99. HttpResponse response;
  100. // 创建一个默认的HTTP客户端
  101. CloseableHttpClient httpClient = HttpClients.createDefault();
  102. if ("GET".equals(method)) {
  103. // 创建一个URIBuilder对象,用于构建包含请求参数的URL
  104. URIBuilder uriBuilder = new URIBuilder(url);
  105. // 获取请求体中的所有键
  106. Set<String> strings = requestBody.keySet();
  107. // 遍历请求体中的键值对,将其添加到URL的查询参数中
  108. for (String string : strings) {
  109. String key = string;
  110. String value = requestBody.getString(key);
  111. uriBuilder.addParameter(key, value);
  112. }
  113. // 创建一个HTTP GET请求
  114. HttpGet httpGet = new HttpGet(uriBuilder.build());
  115. // 遍历请求头信息,将其添加到HTTP GET请求中
  116. for (Entry<String, String> entry : header.entrySet()) {
  117. httpGet.addHeader(entry.getKey(), entry.getValue());
  118. }
  119. // 执行HTTP GET请求
  120. response = httpClient.execute(httpGet);
  121. } else if ("POST".equals(method)) {
  122. // 创建一个HTTP POST请求
  123. HttpPost httpPost = new HttpPost(url);
  124. // 遍历请求头信息,将其添加到HTTP POST请求中
  125. for (Entry<String, String> entry : header.entrySet()) {
  126. httpPost.addHeader(entry.getKey(), entry.getValue());
  127. }
  128. // 创建一个StringEntity对象,将请求体以UTF-8编码包装
  129. StringEntity requestEntity = new StringEntity(requestBody.toString(), "UTF-8");
  130. // 设置请求体到HTTP POST请求中
  131. httpPost.setEntity(requestEntity);
  132. // 执行HTTP POST请求
  133. response = httpClient.execute(httpPost);
  134. } else if ("PUT".equals(method)) {
  135. // 创建一个HTTP PUT请求
  136. HttpPut httpPut = new HttpPut(url);
  137. // 遍历请求头信息,将其添加到HTTP PUT请求中
  138. for (Entry<String, String> entry : header.entrySet()) {
  139. httpPut.addHeader(entry.getKey(), entry.getValue());
  140. }
  141. // 创建一个StringEntity对象,将请求体以UTF-8编码包装
  142. StringEntity requestEntity = new StringEntity(requestBody.toString(), "UTF-8");
  143. // 设置请求体到HTTP PUT请求中
  144. httpPut.setEntity(requestEntity);
  145. // 执行HTTP PUT请求
  146. response = httpClient.execute(httpPut);
  147. } else {
  148. // 如果请求方法不支持,设置错误信息和请求状态到操作日志条目
  149. operateLogEntryInfo.setErrorInfo("Unsupported HTTP method: " + method);
  150. operateLogEntryInfo.setRequestStatus(RequestStatusEnum.ABNORMAL);
  151. // 将操作日志条目添加到条目集合中
  152. entrys.add(operateLogEntryInfo);
  153. try {
  154. // 保存操作日志信息
  155. OperateLogFactory.getLocalInstance(context).save(operateLogInfo);
  156. } catch (BOSException e) {
  157. throw new RuntimeException(e);
  158. } catch (EASBizException e) {
  159. throw new RuntimeException(e);
  160. }
  161. // 抛出不支持的HTTP方法异常
  162. throw new IllegalArgumentException("Unsupported HTTP method: " + method);
  163. }
  164. // 将响应实体转换为字符串
  165. String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
  166. // 将响应字符串解析为JSON对象
  167. responseJson = JSONObject.parseObject(responseBody);
  168. System.out.println(responseBody);
  169. // 用于存储响应数据日志
  170. String dataLog = "";
  171. // 如果响应体字符串长度超过1500,则截取前1500个字符
  172. String string = responseJson.toString();
  173. if (string.length() > 1500) {
  174. dataLog = string.substring(0, 1500);
  175. }else {
  176. dataLog = string.toString();
  177. }
  178. // 设置返回值到操作日志条目
  179. operateLogEntryInfo.setReturnValue(dataLog);
  180. // 获取响应中的状态码
  181. String code = responseJson.getString("code");
  182. // 根据状态码设置请求状态到操作日志条目
  183. if (code == null || !code.equals("200")) {
  184. operateLogEntryInfo.setRequestStatus(RequestStatusEnum.ABNORMAL);
  185. } else {
  186. operateLogEntryInfo.setRequestStatus(RequestStatusEnum.NORMAL);
  187. }
  188. try {
  189. entrys.add(operateLogEntryInfo);
  190. // 保存操作日志信息
  191. OperateLogFactory.getLocalInstance(context).save(operateLogInfo);
  192. } catch (BOSException e) {
  193. throw new RuntimeException(e);
  194. } catch (EASBizException e) {
  195. throw new RuntimeException(e);
  196. }
  197. // 关闭HTTP客户端
  198. httpClient.close();
  199. return responseJson;
  200. }
  201. /**
  202. * 根据业务ID和业务名称获取操作日志信息
  203. *
  204. * @param businessId 业务ID
  205. * @param businessName 业务名称
  206. * @return 操作日志信息对象
  207. */
  208. public OperateLogInfo getOperateLogInfoByBusinessId(String businessId, String businessName) {
  209. if (businessId != null && !businessId.equals("")) {
  210. OperateLogCollection operateLogCollection = null;
  211. try {
  212. // 获取操作日志集合
  213. operateLogCollection = OperateLogFactory.getLocalInstance(context).getOperateLogCollection("where businessId='"+businessId+"' ");
  214. if (operateLogCollection.size() > 0) {
  215. // 如果集合中有元素,返回第一个元素
  216. return operateLogCollection.get(0);
  217. } else {
  218. // 如果集合为空,创建一个新的操作日志信息对象并设置业务ID和业务名称
  219. OperateLogInfo operateLogInfo = new OperateLogInfo();
  220. operateLogInfo.setBusinessId(businessId);
  221. operateLogInfo.setBusinessName(businessName);
  222. return operateLogInfo;
  223. }
  224. } catch (BOSException e) {
  225. throw new RuntimeException(e);
  226. }
  227. } else {
  228. // 如果业务ID为空,创建一个新的操作日志信息对象并设置业务名称
  229. OperateLogInfo operateLogInfo = new OperateLogInfo();
  230. operateLogInfo.setBusinessName(businessName);
  231. return operateLogInfo;
  232. }
  233. }
  234. /**
  235. * 发送HTTP请求并返回JSON格式的响应,请求体为JSONArray类型
  236. *
  237. * @param url 请求的URL地址
  238. * @param header 请求头信息,键值对形式
  239. * @param requestBody 请求体,以JSONArray形式表示
  240. * @param method 请求方法,支持"GET"、"POST"、"PUT"
  241. * @return 服务器返回的JSON对象
  242. * @throws URISyntaxException 如果URL格式不正确
  243. * @throws JSONException 如果JSON解析错误
  244. * @throws IOException 如果发生I/O错误
  245. * @throws ClientProtocolException 如果HTTP协议错误
  246. */
  247. public JSONObject getURL(String url, Map<String, String> header, JSONArray requestBody, String method)
  248. throws URISyntaxException, JSONException, ClientProtocolException, IOException {
  249. // 用于存储服务器返回的JSON对象
  250. JSONObject responseJson = new JSONObject();
  251. HttpResponse response;
  252. // 创建一个默认的HTTP客户端
  253. CloseableHttpClient httpClient = HttpClients.createDefault();
  254. if ("GET".equals(method)) {
  255. // 创建一个URIBuilder对象,用于构建包含请求参数的URL
  256. URIBuilder uriBuilder = new URIBuilder(url);
  257. // 创建一个列表,用于存储请求参数
  258. List paramList = new ArrayList();
  259. // 遍历JSONArray中的元素,将其添加到参数列表中
  260. for (int i = 0; i < requestBody.size(); i++) {
  261. paramList.add(requestBody.get(i));
  262. }
  263. // 将参数列表添加到URL的查询参数中
  264. uriBuilder.addParameters(paramList);
  265. // 创建一个HTTP GET请求
  266. HttpGet httpGet = new HttpGet(uriBuilder.build());
  267. // 遍历请求头信息,将其添加到HTTP GET请求中
  268. for (Entry<String, String> entry : header.entrySet()) {
  269. httpGet.addHeader(entry.getKey(), entry.getValue());
  270. }
  271. // 执行HTTP GET请求
  272. response = httpClient.execute(httpGet);
  273. } else if ("POST".equals(method)) {
  274. // 创建一个HTTP POST请求
  275. HttpPost httpPost = new HttpPost(url);
  276. // 遍历请求头信息,将其添加到HTTP POST请求中
  277. for (Entry<String, String> entry : header.entrySet()) {
  278. httpPost.addHeader(entry.getKey(), entry.getValue());
  279. }
  280. // 创建一个StringEntity对象,将请求体以UTF-8编码包装
  281. StringEntity requestEntity = new StringEntity(requestBody.toString(), "UTF-8");
  282. // 设置请求体到HTTP POST请求中
  283. httpPost.setEntity(requestEntity);
  284. // 执行HTTP POST请求
  285. response = httpClient.execute(httpPost);
  286. } else if ("PUT".equals(method)) {
  287. // 创建一个HTTP PUT请求
  288. HttpPut httpPut = new HttpPut(url);
  289. // 遍历请求头信息,将其添加到HTTP PUT请求中
  290. for (Entry<String, String> entry : header.entrySet()) {
  291. httpPut.addHeader(entry.getKey(), entry.getValue());
  292. }
  293. // 创建一个StringEntity对象,将请求体以UTF-8编码包装
  294. StringEntity requestEntity = new StringEntity(requestBody.toString(), "UTF-8");
  295. // 设置请求体到HTTP PUT请求中
  296. httpPut.setEntity(requestEntity);
  297. // 执行HTTP PUT请求
  298. response = httpClient.execute(httpPut);
  299. } else {
  300. // 如果请求方法不支持,抛出不支持的HTTP方法异常
  301. throw new IllegalArgumentException("Unsupported HTTP method: " + method);
  302. }
  303. // 将响应实体转换为字符串
  304. String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
  305. // 将响应字符串解析为JSON对象
  306. responseJson = JSONObject.parseObject(responseBody);
  307. // 关闭HTTP客户端
  308. httpClient.close();
  309. return responseJson;
  310. }
  311. /**
  312. * 发送编码后的HTTP请求并返回JSON格式的响应
  313. *
  314. * @param url 请求的URL地址
  315. * @param header 请求头信息,键值对形式
  316. * @param requestBody 请求体,以JSONObject形式表示
  317. * @param method 请求方法,支持"GET"、"POST"、"PUT"
  318. * @return 服务器返回的JSON对象
  319. * @throws URISyntaxException 如果URL格式不正确
  320. * @throws JSONException 如果JSON解析错误
  321. * @throws IOException 如果发生I/O错误
  322. * @throws ClientProtocolException 如果HTTP协议错误
  323. */
  324. public JSONObject getURLEncoded(String url, Map<String, String> header, JSONObject requestBody, String method)
  325. throws URISyntaxException, JSONException, ClientProtocolException, IOException {
  326. // 用于存储服务器返回的JSON对象
  327. JSONObject responseJson = new JSONObject();
  328. HttpResponse response;
  329. // 创建一个默认的HTTP客户端
  330. CloseableHttpClient httpClient = HttpClients.createDefault();
  331. if ("GET".equals(method)) {
  332. // 创建一个URIBuilder对象,用于构建包含请求参数的URL
  333. URIBuilder uriBuilder = new URIBuilder(url);
  334. // 创建一个HTTP GET请求
  335. HttpGet httpGet = new HttpGet(uriBuilder.build());
  336. // 遍历请求头信息,将其添加到HTTP GET请求中
  337. for (Entry<String, String> entry : header.entrySet()) {
  338. httpGet.addHeader(entry.getKey(), entry.getValue());
  339. }
  340. // 获取请求体中的所有键
  341. Set<String> strings = requestBody.keySet();
  342. // 遍历请求体中的键值对,将其添加到URL的查询参数中
  343. for (String string : strings) {
  344. String key = string;
  345. String value = requestBody.getString(key);
  346. uriBuilder.addParameter(key, value);
  347. }
  348. // 执行HTTP GET请求
  349. response = httpClient.execute(httpGet);
  350. } else if ("POST".equals(method)) {
  351. // 创建一个HTTP POST请求
  352. HttpPost httpPost = new HttpPost(url);
  353. // 遍历请求头信息,将其添加到HTTP POST请求中
  354. for (Entry<String, String> entry : header.entrySet()) {
  355. httpPost.addHeader(entry.getKey(), entry.getValue());
  356. }
  357. // 创建一个列表,用于存储请求参数
  358. ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
  359. // 获取请求体中的所有键
  360. Set<String> strings = requestBody.keySet();
  361. // 遍历请求体中的键值对,将其添加到参数列表中
  362. for (String string : strings) {
  363. String key = (String) string;
  364. String value = requestBody.getString(key);
  365. list.add(new BasicNameValuePair(key, value));
  366. }
  367. // 创建一个UrlEncodedFormEntity对象,将参数列表以UTF-8编码包装
  368. httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
  369. // 执行HTTP POST请求
  370. response = httpClient.execute(httpPost);
  371. } else if ("PUT".equals(method)) {
  372. // 创建一个HTTP PUT请求
  373. HttpPut httpPut = new HttpPut(url);
  374. // 遍历请求头信息,将其添加到HTTP PUT请求中
  375. for (Entry<String, String> entry : header.entrySet()) {
  376. httpPut.addHeader(entry.getKey(), entry.getValue());
  377. }
  378. // 创建一个列表,用于存储请求参数
  379. ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
  380. // 获取请求体中的所有键
  381. Set<String> strings = requestBody.keySet();
  382. // 遍历请求体中的键值对,将其添加到参数列表中
  383. for (String string : strings) {
  384. String key = (String) string;
  385. String value = requestBody.getString(key);
  386. list.add(new BasicNameValuePair(key, value));
  387. }
  388. // 创建一个UrlEncodedFormEntity对象,将参数列表以UTF-8编码包装
  389. httpPut.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
  390. // 执行HTTP PUT请求
  391. response = httpClient.execute(httpPut);
  392. } else {
  393. // 如果请求方法不支持,抛出不支持的HTTP方法异常
  394. throw new IllegalArgumentException("Unsupported HTTP method: " + method);
  395. }
  396. // 将响应实体转换为字符串
  397. String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
  398. // 将响应字符串解析为JSON对象
  399. responseJson = JSONObject.parseObject(responseBody);
  400. // 关闭HTTP客户端
  401. httpClient.close();
  402. return responseJson;
  403. }
  404. /**
  405. * 通过网络URL获取文件的字节数组
  406. *
  407. * @param urlStr 文件的网络URL地址
  408. * @return 文件的字节数组
  409. * @throws IOException 如果发生I/O错误
  410. */
  411. public byte[] getBytesByNetURL(String urlStr) throws IOException {
  412. // 创建一个URL对象
  413. URL url = new URL(urlStr);
  414. // 创建一个HTTP连接
  415. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  416. // 设置连接超时时间为5秒
  417. conn.setConnectTimeout(5 * 1000);
  418. // 获取输入流,用于读取文件内容
  419. InputStream in = conn.getInputStream();
  420. // 创建一个ByteArrayOutputStream对象,用于存储文件内容
  421. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  422. byte[] buffer = new byte[1024];
  423. int len;
  424. // 循环读取文件内容,并写入到ByteArrayOutputStream中
  425. while ((len = in.read(buffer)) != -1) {
  426. outputStream.write(buffer, 0, len);
  427. }
  428. // 关闭输入流
  429. in.close();
  430. // 返回文件的字节数组
  431. return outputStream.toByteArray();
  432. }
  433. }