AbstractHttpPost.java 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package com.hotent.im.network;
  2. import org.springframework.web.multipart.MultipartFile;
  3. import java.io.*;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * HttpURLConnection发送Post请求工具类
  11. *
  12. * @author yanhongliang
  13. */
  14. public abstract class AbstractHttpPost {
  15. /**
  16. * 网络请求回调
  17. * 抽象方法
  18. * @param response
  19. */
  20. public abstract void complete(Response response);
  21. /**
  22. * post 网络请求
  23. * @param actionUrl 网络请求地址
  24. * @param params 常规参数
  25. * @param files 文件参数
  26. */
  27. public void post(
  28. final String actionUrl,
  29. final Map<String, Object> params,
  30. final HashMap<String, MultipartFile> files) {
  31. sendRequest(actionUrl, params, files);
  32. }
  33. /**
  34. * 通过拼接的方式构造请求内容,实现参数传输以及文件传输
  35. *
  36. * @param actionUrl
  37. * 访问的服务器URL
  38. * @param params
  39. * 普通参数
  40. * @param files
  41. * 文件参数
  42. */
  43. private void sendRequest(
  44. String actionUrl,
  45. Map<String, Object> params,
  46. HashMap<String, MultipartFile> files) {
  47. if (actionUrl == null || actionUrl.isEmpty()) {
  48. return;
  49. }
  50. Response response = new Response(0);
  51. HttpURLConnection conn = null;
  52. InputStreamReader in = null;
  53. try {
  54. String boundary = java.util.UUID.randomUUID().toString();
  55. String prefix = "--", linend = "\r\n";
  56. String multipartFromData = "multipart/form-data";
  57. String charset = "UTF-8";
  58. URL uri = new URL(actionUrl);
  59. conn = (HttpURLConnection) uri.openConnection();
  60. // 缓存的最长时间
  61. conn.setReadTimeout(30 * 1000);
  62. // 允许输入
  63. conn.setDoInput(true);
  64. // 允许输出
  65. conn.setDoOutput(true);
  66. // 不允许使用缓存
  67. conn.setUseCaches(false);
  68. conn.setRequestMethod("POST");
  69. conn.setRequestProperty("connection", "keep-alive");
  70. conn.setRequestProperty("Charsert", "UTF-8");
  71. conn.setRequestProperty("Content-Type", multipartFromData + ";boundary=" + boundary);
  72. DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
  73. // 首先组拼文本类型的参数------start------
  74. if (params != null){
  75. StringBuilder text = new StringBuilder();
  76. for (Map.Entry<String, Object> entry : params.entrySet()) {
  77. text.append(prefix);
  78. text.append(boundary);
  79. text.append(linend);
  80. text.append("Content-Disposition: form-data; name=\"")
  81. .append(entry.getKey())
  82. .append("\"")
  83. .append(linend);
  84. text.append("Content-Type: text/plain; charset=")
  85. .append(charset)
  86. .append(linend);
  87. text.append("Content-Transfer-Encoding: 8bit")
  88. .append(linend);
  89. text.append(linend);
  90. text.append(entry.getValue());
  91. text.append(linend);
  92. }
  93. outStream.write(text.toString().getBytes());
  94. }
  95. // 首先组拼文本类型的参数------end------
  96. // 发送文件数据--------------start-----
  97. if (files != null) {
  98. for (HashMap.Entry<String, MultipartFile> file : files.entrySet()) {
  99. StringBuilder fileBuilder = new StringBuilder();
  100. fileBuilder.append(prefix);
  101. fileBuilder.append(boundary);
  102. fileBuilder.append(linend);
  103. // name是post中传参的键 filename是文件的名称
  104. fileBuilder.append("Content-Disposition: form-data; name=\"file\"; filename=\"")
  105. .append(file.getKey())
  106. .append("\"")
  107. .append(linend);
  108. fileBuilder.append("Content-Type: application/octet-stream; charset=")
  109. .append(charset)
  110. .append(linend);
  111. fileBuilder.append(linend);
  112. outStream.write(fileBuilder.toString().getBytes());
  113. InputStream is = file.getValue().getInputStream();
  114. byte[] buffer = new byte[1024];
  115. int len = 0;
  116. while ((len = is.read(buffer)) != -1) {
  117. outStream.write(buffer, 0, len);
  118. }
  119. is.close();
  120. outStream.write(linend.getBytes());
  121. }
  122. }
  123. // 发送文件数据--------------start-----
  124. // 请求结束标志
  125. byte[] endData = (prefix + boundary + prefix + linend).getBytes();
  126. outStream.write(endData);
  127. outStream.flush();
  128. outStream.close();
  129. long timestamp = System.currentTimeMillis();
  130. response.timestamp = conn.getHeaderFieldDate("Date", 0);
  131. if (response.timestamp != 0) {
  132. response.timestamp += System.currentTimeMillis() - timestamp;
  133. }
  134. // 得到响应码
  135. response.state = conn.getResponseCode();
  136. if (response.state == 200) {
  137. in = new InputStreamReader(conn.getInputStream(), "UTF-8");
  138. // 读取返回数据
  139. BufferedReader reader = new BufferedReader(in);
  140. StringBuilder strBuilder = new StringBuilder();
  141. String line = null;
  142. while ((line = reader.readLine()) != null && !cancel) {
  143. //$NON-NLS-1$
  144. strBuilder.append(line).append("\n");
  145. }
  146. reader.close();
  147. response.content = strBuilder.toString();
  148. }
  149. }catch (Exception e){
  150. response.content = e.getLocalizedMessage();
  151. error(e);
  152. }finally {
  153. if (in != null) {
  154. try {
  155. in.close();
  156. } catch (IOException e) {
  157. e.printStackTrace();
  158. }
  159. }
  160. if (conn != null){
  161. conn.disconnect();
  162. }
  163. response.cancel = cancel;
  164. cancel = false;
  165. complete(response);
  166. }
  167. }
  168. /**
  169. * 取消网络请求
  170. */
  171. private boolean cancel = false;
  172. public void cancel() {
  173. cancel = true;
  174. }
  175. /**
  176. * 异常输出
  177. * @param e 异常
  178. */
  179. private void error(Exception e){
  180. e.printStackTrace();
  181. }
  182. }