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.io.UnsupportedEncodingException;
  26. import java.net.*;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Map.Entry;
  31. import java.util.Set;
  32. /**
  33. * 提供一些常用的HTTP请求和文件下载的辅助方法。
  34. */
  35. public class Helper {
  36. // 上下文对象,用于与Kingdee BOS系统交互
  37. public Context context;
  38. /**
  39. * 构造函数,初始化上下文对象
  40. *
  41. * @param context 上下文对象
  42. */
  43. public Helper(Context context) {
  44. this.context = context;
  45. }
  46. /**
  47. * 发送HTTP请求并返回JSON格式的响应,同时记录操作日志
  48. *
  49. * @param url 请求的URL地址
  50. * @param header 请求头信息,键值对形式
  51. * @param requestBody 请求体,以JSONObject形式表示
  52. * @param method 请求方法,支持"GET"、"POST"、"PUT"
  53. * @param businessId 业务ID
  54. * @param operate 操作名称
  55. * @param businessName 业务名称
  56. * @return 服务器返回的JSON对象
  57. * @throws URISyntaxException 如果URL格式不正确
  58. * @throws JSONException 如果JSON解析错误
  59. * @throws IOException 如果发生I/O错误
  60. * @throws ClientProtocolException 如果HTTP协议错误
  61. */
  62. public JSONObject getURL(String url, Map<String, String> header, JSONObject requestBody, String method,
  63. String businessId, String operate, String businessName)
  64. throws URISyntaxException, JSONException, ClientProtocolException, IOException {
  65. // 根据业务ID和业务名称获取操作日志信息
  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) throws UnsupportedEncodingException {
  209. if (businessId != null && !businessId.equals("")) {
  210. businessId = URLDecoder.decode(businessId,"UTF-8");
  211. OperateLogCollection operateLogCollection = null;
  212. try {
  213. // 获取操作日志集合
  214. operateLogCollection = OperateLogFactory.getLocalInstance(context).getOperateLogCollection("where businessId='"+businessId+"' ");
  215. if (operateLogCollection.size() > 0) {
  216. // 如果集合中有元素,返回第一个元素
  217. return operateLogCollection.get(0);
  218. } else {
  219. // 如果集合为空,创建一个新的操作日志信息对象并设置业务ID和业务名称
  220. OperateLogInfo operateLogInfo = new OperateLogInfo();
  221. operateLogInfo.setBusinessId(businessId);
  222. operateLogInfo.setBusinessName(businessName);
  223. return operateLogInfo;
  224. }
  225. } catch (BOSException e) {
  226. throw new RuntimeException(e);
  227. }
  228. } else {
  229. // 如果业务ID为空,创建一个新的操作日志信息对象并设置业务名称
  230. OperateLogInfo operateLogInfo = new OperateLogInfo();
  231. operateLogInfo.setBusinessName(businessName);
  232. return operateLogInfo;
  233. }
  234. }
  235. /**
  236. * 发送HTTP请求并返回JSON格式的响应,请求体为JSONArray类型
  237. *
  238. * @param url 请求的URL地址
  239. * @param header 请求头信息,键值对形式
  240. * @param requestBody 请求体,以JSONArray形式表示
  241. * @param method 请求方法,支持"GET"、"POST"、"PUT"
  242. * @return 服务器返回的JSON对象
  243. * @throws URISyntaxException 如果URL格式不正确
  244. * @throws JSONException 如果JSON解析错误
  245. * @throws IOException 如果发生I/O错误
  246. * @throws ClientProtocolException 如果HTTP协议错误
  247. */
  248. public JSONObject getURL(String url, Map<String, String> header, JSONArray requestBody, String method)
  249. throws URISyntaxException, JSONException, ClientProtocolException, IOException {
  250. // 用于存储服务器返回的JSON对象
  251. JSONObject responseJson = new JSONObject();
  252. HttpResponse response;
  253. // 创建一个默认的HTTP客户端
  254. CloseableHttpClient httpClient = HttpClients.createDefault();
  255. if ("GET".equals(method)) {
  256. // 创建一个URIBuilder对象,用于构建包含请求参数的URL
  257. URIBuilder uriBuilder = new URIBuilder(url);
  258. // 创建一个列表,用于存储请求参数
  259. List paramList = new ArrayList();
  260. // 遍历JSONArray中的元素,将其添加到参数列表中
  261. for (int i = 0; i < requestBody.size(); i++) {
  262. paramList.add(requestBody.get(i));
  263. }
  264. // 将参数列表添加到URL的查询参数中
  265. uriBuilder.addParameters(paramList);
  266. // 创建一个HTTP GET请求
  267. HttpGet httpGet = new HttpGet(uriBuilder.build());
  268. // 遍历请求头信息,将其添加到HTTP GET请求中
  269. for (Entry<String, String> entry : header.entrySet()) {
  270. httpGet.addHeader(entry.getKey(), entry.getValue());
  271. }
  272. // 执行HTTP GET请求
  273. response = httpClient.execute(httpGet);
  274. } else if ("POST".equals(method)) {
  275. // 创建一个HTTP POST请求
  276. HttpPost httpPost = new HttpPost(url);
  277. // 遍历请求头信息,将其添加到HTTP POST请求中
  278. for (Entry<String, String> entry : header.entrySet()) {
  279. httpPost.addHeader(entry.getKey(), entry.getValue());
  280. }
  281. // 创建一个StringEntity对象,将请求体以UTF-8编码包装
  282. StringEntity requestEntity = new StringEntity(requestBody.toString(), "UTF-8");
  283. // 设置请求体到HTTP POST请求中
  284. httpPost.setEntity(requestEntity);
  285. // 执行HTTP POST请求
  286. response = httpClient.execute(httpPost);
  287. } else if ("PUT".equals(method)) {
  288. // 创建一个HTTP PUT请求
  289. HttpPut httpPut = new HttpPut(url);
  290. // 遍历请求头信息,将其添加到HTTP PUT请求中
  291. for (Entry<String, String> entry : header.entrySet()) {
  292. httpPut.addHeader(entry.getKey(), entry.getValue());
  293. }
  294. // 创建一个StringEntity对象,将请求体以UTF-8编码包装
  295. StringEntity requestEntity = new StringEntity(requestBody.toString(), "UTF-8");
  296. // 设置请求体到HTTP PUT请求中
  297. httpPut.setEntity(requestEntity);
  298. // 执行HTTP PUT请求
  299. response = httpClient.execute(httpPut);
  300. } else {
  301. // 如果请求方法不支持,抛出不支持的HTTP方法异常
  302. throw new IllegalArgumentException("Unsupported HTTP method: " + method);
  303. }
  304. // 将响应实体转换为字符串
  305. String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
  306. // 将响应字符串解析为JSON对象
  307. responseJson = JSONObject.parseObject(responseBody);
  308. // 关闭HTTP客户端
  309. httpClient.close();
  310. return responseJson;
  311. }
  312. /**
  313. * 发送编码后的HTTP请求并返回JSON格式的响应
  314. *
  315. * @param url 请求的URL地址
  316. * @param header 请求头信息,键值对形式
  317. * @param requestBody 请求体,以JSONObject形式表示
  318. * @param method 请求方法,支持"GET"、"POST"、"PUT"
  319. * @return 服务器返回的JSON对象
  320. * @throws URISyntaxException 如果URL格式不正确
  321. * @throws JSONException 如果JSON解析错误
  322. * @throws IOException 如果发生I/O错误
  323. * @throws ClientProtocolException 如果HTTP协议错误
  324. */
  325. public JSONObject getURLEncoded(String url, Map<String, String> header, JSONObject requestBody, String method)
  326. throws URISyntaxException, JSONException, ClientProtocolException, IOException {
  327. // 用于存储服务器返回的JSON对象
  328. JSONObject responseJson = new JSONObject();
  329. HttpResponse response;
  330. // 创建一个默认的HTTP客户端
  331. CloseableHttpClient httpClient = HttpClients.createDefault();
  332. if ("GET".equals(method)) {
  333. // 创建一个URIBuilder对象,用于构建包含请求参数的URL
  334. URIBuilder uriBuilder = new URIBuilder(url);
  335. // 创建一个HTTP GET请求
  336. HttpGet httpGet = new HttpGet(uriBuilder.build());
  337. // 遍历请求头信息,将其添加到HTTP GET请求中
  338. for (Entry<String, String> entry : header.entrySet()) {
  339. httpGet.addHeader(entry.getKey(), entry.getValue());
  340. }
  341. // 获取请求体中的所有键
  342. Set<String> strings = requestBody.keySet();
  343. // 遍历请求体中的键值对,将其添加到URL的查询参数中
  344. for (String string : strings) {
  345. String key = string;
  346. String value = requestBody.getString(key);
  347. uriBuilder.addParameter(key, value);
  348. }
  349. // 执行HTTP GET请求
  350. response = httpClient.execute(httpGet);
  351. } else if ("POST".equals(method)) {
  352. // 创建一个HTTP POST请求
  353. HttpPost httpPost = new HttpPost(url);
  354. // 遍历请求头信息,将其添加到HTTP POST请求中
  355. for (Entry<String, String> entry : header.entrySet()) {
  356. httpPost.addHeader(entry.getKey(), entry.getValue());
  357. }
  358. // 创建一个列表,用于存储请求参数
  359. ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
  360. // 获取请求体中的所有键
  361. Set<String> strings = requestBody.keySet();
  362. // 遍历请求体中的键值对,将其添加到参数列表中
  363. for (String string : strings) {
  364. String key = (String) string;
  365. String value = requestBody.getString(key);
  366. list.add(new BasicNameValuePair(key, value));
  367. }
  368. // 创建一个UrlEncodedFormEntity对象,将参数列表以UTF-8编码包装
  369. httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
  370. // 执行HTTP POST请求
  371. response = httpClient.execute(httpPost);
  372. } else if ("PUT".equals(method)) {
  373. // 创建一个HTTP PUT请求
  374. HttpPut httpPut = new HttpPut(url);
  375. // 遍历请求头信息,将其添加到HTTP PUT请求中
  376. for (Entry<String, String> entry : header.entrySet()) {
  377. httpPut.addHeader(entry.getKey(), entry.getValue());
  378. }
  379. // 创建一个列表,用于存储请求参数
  380. ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
  381. // 获取请求体中的所有键
  382. Set<String> strings = requestBody.keySet();
  383. // 遍历请求体中的键值对,将其添加到参数列表中
  384. for (String string : strings) {
  385. String key = (String) string;
  386. String value = requestBody.getString(key);
  387. list.add(new BasicNameValuePair(key, value));
  388. }
  389. // 创建一个UrlEncodedFormEntity对象,将参数列表以UTF-8编码包装
  390. httpPut.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
  391. // 执行HTTP PUT请求
  392. response = httpClient.execute(httpPut);
  393. } else {
  394. // 如果请求方法不支持,抛出不支持的HTTP方法异常
  395. throw new IllegalArgumentException("Unsupported HTTP method: " + method);
  396. }
  397. // 将响应实体转换为字符串
  398. String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
  399. // 将响应字符串解析为JSON对象
  400. responseJson = JSONObject.parseObject(responseBody);
  401. // 关闭HTTP客户端
  402. httpClient.close();
  403. return responseJson;
  404. }
  405. /**
  406. * 通过网络URL获取文件的字节数组
  407. *
  408. * @param urlStr 文件的网络URL地址
  409. * @return 文件的字节数组
  410. * @throws IOException 如果发生I/O错误
  411. */
  412. public byte[] getBytesByNetURL(String urlStr) throws IOException {
  413. // 创建一个URL对象
  414. URL url = new URL(urlStr);
  415. // 创建一个HTTP连接
  416. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  417. // 设置连接超时时间为5秒
  418. conn.setConnectTimeout(5 * 1000);
  419. // 获取输入流,用于读取文件内容
  420. InputStream in = conn.getInputStream();
  421. // 创建一个ByteArrayOutputStream对象,用于存储文件内容
  422. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  423. byte[] buffer = new byte[1024];
  424. int len;
  425. // 循环读取文件内容,并写入到ByteArrayOutputStream中
  426. while ((len = in.read(buffer)) != -1) {
  427. outputStream.write(buffer, 0, len);
  428. }
  429. // 关闭输入流
  430. in.close();
  431. // 返回文件的字节数组
  432. return outputStream.toByteArray();
  433. }
  434. }