HttpUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package me.zhengjie.base.util;
  2. import java.io.*;
  3. import java.net.*;
  4. import java.text.MessageFormat;
  5. import java.util.*;
  6. import com.alibaba.fastjson.JSONObject;
  7. import cfca.trustsign.common.vo.cs.SignKeywordVO;
  8. import cfca.trustsign.common.vo.cs.UploadSignInfoVO;
  9. public class HttpUtil {
  10. /**
  11. * 默认超时时间为30秒
  12. */
  13. private static int DEFAULT_TIME_OUT = 1800000000;
  14. /**
  15. * jdk 原生 http post 请求,默认超时时间为30秒
  16. *
  17. * @param url 请求地址
  18. * @param json 入参String
  19. * @return respone的body
  20. */
  21. public static String sendPost(String url, String json) {
  22. return sendPost(url, json, DEFAULT_TIME_OUT);
  23. }
  24. /**
  25. * JDK原生post请求
  26. *
  27. * @param url 访问地址
  28. * @param body request请求体
  29. * @param timeOut 超时时间,单位毫秒
  30. * @return 响应体string
  31. */
  32. public static String sendPost(String url, String body, int timeOut) {
  33. URLConnection conn = null;
  34. try {
  35. URL realUrl = new URL(url);
  36. // 打开和URL之间的连接
  37. conn = realUrl.openConnection();
  38. // 设置通用的请求头属性
  39. conn.setRequestProperty("Content-Type", "application/json");
  40. conn.setRequestProperty("accept", "*/*");
  41. conn.setRequestProperty("connection", "Keep-Alive");
  42. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  43. conn.setRequestProperty("charsert", "utf-8");
  44. conn.setConnectTimeout(timeOut);
  45. conn.setReadTimeout(timeOut);
  46. // 发送POST请求必须设置如下两行
  47. conn.setDoOutput(true);
  48. conn.setDoInput(true);
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. return sendRequest(conn, body, "utf-8");
  53. }
  54. private static String sendRequest(URLConnection conn, String body, String charSet) {
  55. PrintWriter out = null;
  56. InputStreamReader ir;
  57. BufferedReader in = null;// 读取响应输入流
  58. StringBuilder stringBuilder = null;
  59. try {
  60. if (body != null) {
  61. out = new PrintWriter(conn.getOutputStream()); // 用PrintWriter进行包装
  62. out.println(body);
  63. // flush输出流的缓冲
  64. out.flush();
  65. }
  66. ir = new InputStreamReader(conn.getInputStream(), charSet);
  67. in = new BufferedReader(ir);
  68. String line;
  69. stringBuilder = new StringBuilder();
  70. while ((line = in.readLine()) != null) {
  71. stringBuilder.append(line);
  72. }
  73. } catch (IOException e1) {
  74. e1.printStackTrace();
  75. }
  76. // 使用finally块来关闭输出流、输入流
  77. finally {
  78. try {
  79. if (out != null) {
  80. out.close();
  81. }
  82. if (in != null) {
  83. in.close();
  84. }
  85. } catch (Exception ex) {
  86. ex.printStackTrace();
  87. }
  88. }
  89. if (stringBuilder == null)
  90. return null;
  91. return stringBuilder.toString();
  92. }
  93. /***
  94. * 向指定URL发送POST方法的请求
  95. *
  96. * @param apiUrl
  97. * @param data
  98. * @param headers
  99. * @param encoding
  100. * @return
  101. * @throws Exception
  102. */
  103. public static String sendPOST(String apiUrl, String data, LinkedHashMap<String, String> headers, String encoding) throws Exception {
  104. // 获得响应内容
  105. String http_RespContent = null;
  106. HttpURLConnection httpURLConnection = null;
  107. int http_StatusCode = 0;
  108. String http_RespMessage = null;
  109. try {
  110. // 建立连接
  111. URL url = new URL(apiUrl);
  112. httpURLConnection = (HttpURLConnection) url.openConnection();
  113. // 需要输出
  114. httpURLConnection.setDoOutput(true);
  115. // 需要输入
  116. httpURLConnection.setDoInput(true);
  117. // 不允许缓存
  118. httpURLConnection.setUseCaches(false);
  119. // HTTP请求方式
  120. httpURLConnection.setRequestMethod("POST");
  121. // 设置Headers
  122. if (null != headers) {
  123. for (String key : headers.keySet()) {
  124. httpURLConnection.setRequestProperty(key, headers.get(key));
  125. }
  126. }
  127. // 连接会话
  128. httpURLConnection.connect();
  129. if (data != null) {
  130. // 建立输入流,向指向的URL传入参数
  131. DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
  132. // 设置请求参数
  133. dos.write(data.getBytes(encoding));
  134. dos.flush();
  135. dos.close();
  136. }
  137. // 获得响应状态(HTTP状态码)
  138. http_StatusCode = httpURLConnection.getResponseCode();
  139. // 获得响应消息(HTTP状态码描述)
  140. http_RespMessage = httpURLConnection.getResponseMessage();
  141. // 获得响应内容
  142. if (HttpURLConnection.HTTP_OK == http_StatusCode) {
  143. // 返回响应结果
  144. http_RespContent = getResponseContent(httpURLConnection);
  145. } else {
  146. // 返回非200状态时响应结果
  147. http_RespContent = getErrorResponseContent(httpURLConnection);
  148. String msg =
  149. MessageFormat.format("请求失败: Http状态码 = {0} , {1}", http_StatusCode, http_RespMessage);
  150. System.out.println(msg);
  151. }
  152. } catch (UnknownHostException e) {
  153. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  154. Exception ex = new Exception(message);
  155. ex.initCause(e);
  156. throw ex;
  157. } catch (MalformedURLException e) {
  158. String message = MessageFormat.format("格式错误的URL: {0}", e.getMessage());
  159. Exception ex = new Exception(message);
  160. ex.initCause(e);
  161. throw ex;
  162. } catch (IOException e) {
  163. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  164. Exception ex = new Exception(message);
  165. ex.initCause(e);
  166. throw ex;
  167. } catch (Exception e) {
  168. String message = MessageFormat.format("网络请求时发生异常: {0}", e.getMessage());
  169. Exception ex = new Exception(message);
  170. ex.initCause(e);
  171. throw ex;
  172. } finally {
  173. if (null != httpURLConnection) {
  174. httpURLConnection.disconnect();
  175. }
  176. }
  177. return http_RespContent;
  178. }
  179. /***
  180. * 读取HttpResponse响应内容
  181. *
  182. * @param httpURLConnection
  183. * @return
  184. * @throws UnsupportedEncodingException
  185. * @throws IOException
  186. */
  187. private static String getErrorResponseContent(HttpURLConnection httpURLConnection)
  188. throws UnsupportedEncodingException, IOException {
  189. StringBuffer contentBuffer = null;
  190. BufferedReader responseReader = null;
  191. try {
  192. contentBuffer = new StringBuffer();
  193. String readLine = null;
  194. responseReader =
  195. new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
  196. while ((readLine = responseReader.readLine()) != null) {
  197. contentBuffer.append(readLine);
  198. }
  199. } finally {
  200. if (null != responseReader) {
  201. responseReader.close();
  202. }
  203. }
  204. return contentBuffer.toString();
  205. }
  206. /***
  207. * 读取HttpResponse响应内容
  208. *
  209. * @param httpURLConnection
  210. * @return
  211. * @throws UnsupportedEncodingException
  212. * @throws IOException
  213. */
  214. private static String getResponseContent(HttpURLConnection httpURLConnection)
  215. throws UnsupportedEncodingException, IOException {
  216. StringBuffer contentBuffer = null;
  217. BufferedReader responseReader = null;
  218. try {
  219. contentBuffer = new StringBuffer();
  220. String readLine = null;
  221. responseReader =
  222. new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
  223. while ((readLine = responseReader.readLine()) != null) {
  224. contentBuffer.append(readLine);
  225. }
  226. } finally {
  227. if (null != responseReader) {
  228. responseReader.close();
  229. }
  230. }
  231. return contentBuffer.toString();
  232. }
  233. /**
  234. * 上传文件
  235. *
  236. * @param url
  237. * @param header
  238. * @param filePath
  239. * @return
  240. */
  241. public static String postFile(String url, Map<String, String> header, String filePath) {
  242. HttpURLConnection conn = null;
  243. OutputStream out = null;
  244. String respContent = "";
  245. try {
  246. URL realUrl = new URL(url);
  247. // 打开和URL之间的连接
  248. conn = (HttpURLConnection) realUrl.openConnection();
  249. // 设置通用的请求头属性
  250. conn.setRequestProperty("Content-Type", header.get("contentType"));
  251. conn.setRequestProperty("Content-MD5", header.get("contentMD5"));
  252. // 发送POST请求必须设置如下两行
  253. conn.setDoOutput(true);
  254. conn.setDoInput(true);
  255. conn.setRequestMethod("PUT");
  256. conn.connect();
  257. // 上传文件内容
  258. out = new DataOutputStream(conn.getOutputStream());
  259. File file = new File(filePath);
  260. DataInputStream fileIS = new DataInputStream(new FileInputStream(file));
  261. int bytes = 0;
  262. byte[] bufferOut = new byte[1024];
  263. while ((bytes = fileIS.read(bufferOut)) != -1) {
  264. out.write(bufferOut, 0, bytes);
  265. }
  266. fileIS.close();
  267. out.flush();
  268. out.close();
  269. // 获取返回信息
  270. int statusCode = conn.getResponseCode();
  271. String respMessage = conn.getResponseMessage();
  272. // 获得响应内容
  273. if (HttpURLConnection.HTTP_OK == statusCode) {
  274. // 返回响应结果
  275. respContent = getResponseContent(conn);
  276. } else {
  277. // 返回非200状态时响应结果
  278. respContent = getErrorResponseContent(conn);
  279. String msg = MessageFormat.format("请求失败: Http状态码 = {0} , {1}", statusCode, respMessage);
  280. System.out.println(msg);
  281. }
  282. } catch (IOException e) {
  283. e.printStackTrace();
  284. } finally {
  285. try {
  286. if (out != null) {
  287. out.close();
  288. }
  289. if (conn != null) {
  290. conn.disconnect();
  291. }
  292. } catch (Exception ex) {
  293. ex.printStackTrace();
  294. }
  295. }
  296. return respContent;
  297. }
  298. public static void main(String[] args) throws Exception {
  299. int i = 0;
  300. String pdf = "gzs.pdf";
  301. String localUrl = "https://flowbb.show.xjrkj.com/demo";
  302. // String localUrl = "http://localhost:8000/demo";
  303. List<UploadSignInfoVO> notaryUserInfos = new ArrayList<>();
  304. // --------------------------------------------------------------------------------------
  305. UploadSignInfoVO xj = new UploadSignInfoVO();
  306. xj.setUserId("E06DAAB5F6894542E05312016B0AC8F1");
  307. xj.setSealId("E06DAB4AFAEF4DB7E05311016B0A5154");
  308. xj.setLocation("210.74.41.0");
  309. xj.setAuthorizationTime("20220214171200");
  310. notaryUserInfos.add(xj);
  311. // UploadSignInfoVO ttt = new UploadSignInfoVO();
  312. // ttt.setUserId("E658B207485F141AE05311016B0A5F19");
  313. // ttt.setSealId("E658C5DBBAF1340DE05311016B0A3C4D");
  314. // ttt.setLocation("210.74.41.0");
  315. // ttt.setAuthorizationTime("20220214171200");
  316. // notaryUserInfos.add(ttt);
  317. UploadSignInfoVO wcc = new UploadSignInfoVO();
  318. wcc.setUserId("E150B42F789F53D8E05311016B0A24B0");
  319. wcc.setSealId("E150B90286FA6E31E05312016B0A03F2");
  320. wcc.setLocation("210.74.41.0");
  321. wcc.setAuthorizationTime("20220214171200");
  322. notaryUserInfos.add(wcc);
  323. for (UploadSignInfoVO user : notaryUserInfos) {
  324. String x = String.valueOf(10 + i * 70);
  325. i++;
  326. SignKeywordVO keywordNotaryUser = CFCACertUtil.getSignKeywork("签章:", x, "0", "80", "40");
  327. CFCACertUtil.setSignInfoDefault(user, keywordNotaryUser);
  328. }
  329. // --------------------------------------------------------------------------------------
  330. // SignKeywordVO keywordNotaryOffice = CFCACertUtil.getSignKeywork("签章", "0", "0", "150", "150");
  331. // if (notaryOffice != null) {
  332. // setSignInfoDefault(notaryOffice, keywordNotaryOffice);
  333. // signInfos.add(notaryOffice);
  334. // }
  335. String result = HttpUtil.sendPost(localUrl + "/notarySign?fileName=" + pdf,
  336. JSONObject.toJSONString(notaryUserInfos));
  337. JSONObject jsonObj = JSONObject.parseObject(result);
  338. System.out.println(jsonObj.getString("msg") + ".pdf");
  339. Map<String, String> param = new HashMap<String, String>();
  340. param.put("contractNo", jsonObj.getString("msg"));
  341. result = HttpUtil.sendPost(localUrl + "/download", JSONObject.toJSONString(param));
  342. System.out.println(result);
  343. // System.out.println("用户近6个月平均话费评分:" + result);
  344. }
  345. }