HttpUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package com.dk.common.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.dk.common.response.ResponseCodeEnum;
  5. import com.dk.common.response.ResponseResultUtil;
  6. import com.dk.common.response.ResponseResultVO;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.io.FileUtils;
  9. import org.apache.http.Consts;
  10. import org.apache.http.entity.mime.HttpMultipartMode;
  11. import org.springframework.http.client.MultipartBodyBuilder;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import org.apache.http.HttpEntity;
  14. import org.apache.http.client.methods.CloseableHttpResponse;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.entity.ContentType;
  17. import org.apache.http.entity.mime.MultipartEntityBuilder;
  18. import org.apache.http.impl.client.CloseableHttpClient;
  19. import org.apache.http.impl.client.HttpClients;
  20. import org.apache.http.util.EntityUtils;
  21. import java.io.*;
  22. import java.net.HttpURLConnection;
  23. import java.net.SocketTimeoutException;
  24. import java.net.URL;
  25. import java.nio.charset.Charset;
  26. import java.nio.charset.StandardCharsets;
  27. import java.util.Map;
  28. /**
  29. * @author H_x_d
  30. * @date_time 2020-07-16 11:44
  31. * @description com.dongke.base.util.HttpHelper.java
  32. */
  33. @Slf4j
  34. public class HttpUtils {
  35. public static ResponseResultVO<JSONObject> post(String url) {
  36. return httpPost(url, null, false, null, null, null);
  37. }
  38. public static ResponseResultVO<JSONObject> post(String url, Object object) {
  39. return httpPost(url, object, false, null, null, null);
  40. }
  41. public static ResponseResultVO<JSONObject> post(String url, Map<String, String> requestProperty) {
  42. return httpPost(url, null, false, null, requestProperty, null);
  43. }
  44. public static ResponseResultVO<JSONObject> post(String url, Object object, Integer overTime) {
  45. return httpPost(url, object, false, null, null, overTime);
  46. }
  47. public static ResponseResultVO<JSONObject> post(String url, Object object, Map<String, String> requestProperty) {
  48. return httpPost(url, object, false, null, requestProperty, null);
  49. }
  50. public static ResponseResultVO<JSONObject> post(String url, Object object, Map<String, String> requestProperty, Integer overTime) {
  51. return httpPost(url, object, false, null, requestProperty, overTime);
  52. }
  53. public static ResponseResultVO<String> postReturnFile(String url, Object object, String fileUrl) {
  54. return httpPost(url, object, true, fileUrl, null, null);
  55. }
  56. public static ResponseResultVO httpPost(String url, Object object, boolean returnFile, String fileUrl, Map<String, String> requestProperty, Integer overTime) {
  57. log.info("post_url-> " + url);
  58. InputStream inputStream = null;
  59. HttpURLConnection connection = null;
  60. FileOutputStream fos = null;
  61. ByteArrayOutputStream boa = null;
  62. OutputStreamWriter outputStreamWriter = null;
  63. try {
  64. //获取位置服务的地址
  65. URL u = new URL(url);
  66. //打开连接
  67. connection = (HttpURLConnection) u.openConnection();
  68. connection.setDoOutput(true);
  69. connection.setDoInput(true);
  70. connection.setRequestMethod("POST");
  71. connection.setUseCaches(false);
  72. connection.setInstanceFollowRedirects(true);
  73. // 超时时间
  74. if (overTime==null) {
  75. connection.setConnectTimeout(3000);
  76. connection.setReadTimeout(120000);
  77. }else{
  78. connection.setConnectTimeout(overTime);
  79. connection.setReadTimeout(overTime);
  80. }
  81. connection.setRequestProperty("Content-Type", "application/json;charset:utf-8");
  82. if (requestProperty != null) {
  83. for (String key : requestProperty.keySet()) {
  84. connection.setRequestProperty(key, requestProperty.get(key));
  85. }
  86. }
  87. connection.connect();
  88. outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
  89. log.info("post_param-> \n" + JSONObject.toJSONString(object));
  90. outputStreamWriter.append(JSONObject.toJSONString(object));
  91. outputStreamWriter.flush();
  92. outputStreamWriter.close();
  93. int responseCode = connection.getResponseCode();
  94. log.info("responseCode-> " + responseCode);
  95. if (responseCode == HttpURLConnection.HTTP_OK) {
  96. inputStream = connection.getInputStream();
  97. if (returnFile) {
  98. File file = new File(fileUrl);
  99. fos = new FileOutputStream(file);
  100. byte[] buffer = new byte[4096];
  101. int len = -1;
  102. while ((len = inputStream.read(buffer)) != -1) {
  103. fos.write(buffer, 0, len);
  104. }
  105. fos.close();
  106. inputStream.close();
  107. log.info("post_result-> \n file url:{}", fileUrl);
  108. return ResponseResultUtil.success(fileUrl);
  109. } else {
  110. boa = new ByteArrayOutputStream();
  111. int len = 0;
  112. byte[] buffer = new byte[1024];
  113. while ((len = inputStream.read(buffer)) != -1) {
  114. boa.write(buffer, 0, len);
  115. }
  116. // inputStream.close();
  117. // boa.close();
  118. byte[] result = boa.toByteArray();
  119. String temp = new String(result);
  120. String res = "";
  121. // 识别编码
  122. if (temp.contains("gb2312")) {
  123. log.info("解码类型:gb2312");
  124. res = new String(result, "gb2312");
  125. } else {
  126. // log.info("解码类型:utf-8");
  127. res = new String(result, StandardCharsets.UTF_8);
  128. }
  129. log.info("post_result-> \n" + res);
  130. return ResponseResultUtil.success(JSONObject.parseObject(res));
  131. //将流转换为字符串。
  132. // byte[] b = new byte[4096];
  133. // for (int n; (n = inputStream.read(b)) != -1;) {
  134. // out.append(new String(b, 0, n, StandardCharsets.UTF_8));
  135. // }
  136. // inputStream.close();
  137. // log.info("post_result-> \n"+out.toString());
  138. // return ResponseResultUtil.success(JSONObject.parseObject(out.toString()));
  139. }
  140. } else {
  141. log.error("post_code-> " + responseCode);
  142. return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL, String.valueOf(responseCode));
  143. }
  144. } catch (SocketTimeoutException e) {
  145. log.error("post_error:{}", e.toString(), e);
  146. return ResponseResultUtil.error(ResponseCodeEnum.SERVER_CONNECT_OUT, e.toString());
  147. } catch (Exception e) {
  148. log.error("post_error:{}", e.toString(), e);
  149. return ResponseResultUtil.error(ResponseCodeEnum.SERVER_ERROR, e.toString());
  150. } finally {
  151. // 断开连接、关闭流
  152. if (connection!=null){
  153. connection.disconnect();
  154. }
  155. try {
  156. if (inputStream!=null){
  157. inputStream.close();
  158. }
  159. if (fos!=null){
  160. fos.close();
  161. }
  162. if (boa!=null){
  163. boa.close();
  164. }
  165. if (outputStreamWriter!=null){
  166. outputStreamWriter.close();
  167. }
  168. } catch (IOException e) {
  169. log.error(e.toString(), e);
  170. }
  171. }
  172. }
  173. public static ResponseResultVO<JSONObject> get(String url) {
  174. return httpGet(url, null, null);
  175. }
  176. public static ResponseResultVO<JSONObject> get(String url, Map<String, String> requestProperty) {
  177. return httpGet(url, requestProperty, null);
  178. }
  179. public static ResponseResultVO<JSONObject> get(String url, Integer overTime) {
  180. return httpGet(url, null, overTime);
  181. }
  182. public static ResponseResultVO<JSONObject> get(String url, Map<String, String> requestProperty, Integer overTime) {
  183. return httpGet(url, requestProperty, overTime);
  184. }
  185. public static ResponseResultVO<JSONObject> httpGet(String url, Map<String, String> requestProperty, Integer overTime) {
  186. log.info("get_url-> " + url);
  187. BufferedReader br = null;
  188. HttpURLConnection connection = null;
  189. try {
  190. URL u = new URL(url);
  191. connection = (HttpURLConnection) u.openConnection();
  192. // 超时时间
  193. if (overTime==null) {
  194. connection.setConnectTimeout(3000);
  195. connection.setReadTimeout(120000);
  196. }else{
  197. connection.setConnectTimeout(overTime);
  198. connection.setReadTimeout(overTime);
  199. }
  200. connection.setRequestProperty("Content-Type", "application/json;charset:utf-8");
  201. if (requestProperty != null) {
  202. for (String key : requestProperty.keySet()) {
  203. connection.setRequestProperty(key, requestProperty.get(key));
  204. }
  205. }
  206. connection.connect();// 连接会话
  207. // 获取输入流
  208. br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
  209. String line;
  210. StringBuilder sb = new StringBuilder();
  211. while ((line = br.readLine()) != null) {
  212. sb.append(line);
  213. }
  214. // br.close();// 关闭流
  215. // connection.disconnect();// 断开连接
  216. log.info("get_result-> \n" + sb.toString());
  217. return ResponseResultUtil.success(JSONObject.parseObject(sb.toString()));
  218. } catch (SocketTimeoutException e) {
  219. log.error("get_error:{}", e.toString(), e);
  220. return ResponseResultUtil.error(ResponseCodeEnum.SERVER_CONNECT_OUT, e.toString());
  221. } catch (Exception e) {
  222. log.error("get_error:{}", e.toString(), e);
  223. return ResponseResultUtil.error(ResponseCodeEnum.SERVER_ERROR, e.toString());
  224. } finally {
  225. // 断开连接 关闭流
  226. if (connection!=null){
  227. connection.disconnect();
  228. }
  229. try {
  230. if (br!=null) {
  231. br.close();
  232. }
  233. } catch (IOException e) {
  234. log.error(e.toString(), e);
  235. }
  236. }
  237. }
  238. public static ResponseResultVO<JSONObject> postFile(String url, MultipartFile file) {
  239. return postFormData(url, null, file);
  240. }
  241. public static ResponseResultVO<JSONObject> postFile(String url, Object object, MultipartFile file) {
  242. return postFormData(url, object, file);
  243. }
  244. public static ResponseResultVO<JSONObject> postForm(String url, Object object) {
  245. return postFormData(url, object, null);
  246. }
  247. public static ResponseResultVO<JSONObject> postFormData(String url, Object object, MultipartFile file) {
  248. log.info("postFormData, url:\n{}", url);
  249. CloseableHttpClient httpClient = HttpClients.createDefault();
  250. HttpPost httpPost = new HttpPost(url);
  251. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  252. if (object!=null){
  253. JSONObject param = JSONObject.parseObject(JSONObject.toJSONString(object));
  254. param.keySet().forEach(key -> {
  255. log.info("key:{},value:{}",key,param.getString(key));
  256. builder.addTextBody(key, param.getString(key), ContentType.create("text/plain", StandardCharsets.UTF_8));
  257. });
  258. }
  259. try {
  260. File f = null;
  261. if (file != null && file.getOriginalFilename() == null) {
  262. return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), "文件不存在");
  263. } else if (file != null && file.getOriginalFilename() != null) {
  264. log.info("post form data, file->\nname:{},size:{},", file.getName(), file.getSize());
  265. f = new File(file.getOriginalFilename());
  266. FileUtils.copyInputStreamToFile(file.getInputStream(), f);
  267. builder.addBinaryBody(
  268. "file",
  269. new FileInputStream(f),
  270. ContentType.APPLICATION_OCTET_STREAM,
  271. f.getName()
  272. );
  273. }
  274. HttpEntity multipart = builder.build();
  275. httpPost.setEntity(multipart);
  276. CloseableHttpResponse response = httpClient.execute(httpPost);
  277. HttpEntity responseEntity = response.getEntity();
  278. String sResponse = EntityUtils.toString(responseEntity, "UTF-8");
  279. log.info("post form data response->\n{}", sResponse);
  280. JSONObject res = JSONObject.parseObject(sResponse);
  281. // 会在本地产生临时文件,用完后需要删除
  282. if (f != null && f.exists()) {
  283. f.delete();
  284. }
  285. return ResponseResultUtil.success(res);
  286. } catch (SocketTimeoutException e) {
  287. log.error("postFormData_error:{}", e.toString(), e);
  288. return ResponseResultUtil.error(ResponseCodeEnum.SERVER_CONNECT_OUT, e.toString());
  289. } catch (Exception e) {
  290. log.error(e.toString(), e);
  291. return ResponseResultUtil.error(ResponseCodeEnum.SERVER_ERROR, e.toString());
  292. }
  293. }
  294. }