From 16c5cf4cdb5b6b9f1fcf9718b94dbdb628439479 Mon Sep 17 00:00:00 2001 From: liuchengqian Date: Tue, 14 Feb 2023 14:08:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xkrs/common/account/JwtLoginFilter.java | 1 - .../java/com/xkrs/common/tool/TokenUtil.java | 13 +- .../java/com/xkrs/utils/CommonConstant.java | 3 - .../java/com/xkrs/utils/DateTimeUtil.java | 168 +---------- src/main/java/com/xkrs/utils/FileUtil.java | 34 --- .../com/xkrs/utils/FirePointCodeUtils.java | 2 +- .../java/com/xkrs/utils/GaoDeApiUtil.java | 3 - .../java/com/xkrs/utils/HttpClientUtils.java | 4 - src/main/java/com/xkrs/utils/IpUtil.java | 43 --- src/main/java/com/xkrs/utils/RandomUtil.java | 2 - src/main/java/com/xkrs/utils/RequestUtil.java | 260 ------------------ .../java/com/xkrs/utils/RestTemplateUtil.java | 94 ------- .../com/xkrs/utils/WDHttpClientUtils.java | 81 ------ src/main/java/com/xkrs/utils/XlsxUtil.java | 2 +- .../service/impl/WeatherDataServiceImpl.java | 1 - 15 files changed, 7 insertions(+), 704 deletions(-) delete mode 100644 src/main/java/com/xkrs/utils/IpUtil.java delete mode 100644 src/main/java/com/xkrs/utils/RequestUtil.java delete mode 100644 src/main/java/com/xkrs/utils/RestTemplateUtil.java diff --git a/src/main/java/com/xkrs/common/account/JwtLoginFilter.java b/src/main/java/com/xkrs/common/account/JwtLoginFilter.java index d5c1b85..2edec01 100644 --- a/src/main/java/com/xkrs/common/account/JwtLoginFilter.java +++ b/src/main/java/com/xkrs/common/account/JwtLoginFilter.java @@ -4,7 +4,6 @@ import com.xkrs.common.encapsulation.OutputEncapsulation; import com.xkrs.common.encapsulation.PromptMessageEnum; import com.xkrs.straw.model.entity.SysUserEntity; import com.xkrs.straw.service.SysUserService; -import com.xkrs.utils.IpUtil; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; diff --git a/src/main/java/com/xkrs/common/tool/TokenUtil.java b/src/main/java/com/xkrs/common/tool/TokenUtil.java index 0c4a642..0862cec 100644 --- a/src/main/java/com/xkrs/common/tool/TokenUtil.java +++ b/src/main/java/com/xkrs/common/tool/TokenUtil.java @@ -11,7 +11,6 @@ import java.util.List; /** * token工具 - * @author tajochen */ public class TokenUtil { /** @@ -19,9 +18,7 @@ public class TokenUtil { */ static public final String TOKEN_PREFIX = "Bearer"; - static public final String SECRETKEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U30345" + - "HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9LXUJ" + - "OI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8"; + static public final String SECRETKEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U30345" + "HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9LXUJ" + "OI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8"; static SecretKey key = Keys.hmacShaKeyFor(SECRETKEY.getBytes()); @@ -30,16 +27,14 @@ public class TokenUtil { if (token != null) { try { // 解析 Token - Claims claims = Jwts.parserBuilder() - .setSigningKey(key).build() + Claims claims = Jwts.parserBuilder().setSigningKey(key).build() // 去掉 Bearer - .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) - .getBody(); + .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody(); // 获取用户名 userName = claims.getSubject(); // 获取权限 List authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("auths")); - } catch(Exception e) { + } catch (Exception e) { // the sub field was missing or did not have a 'jsmith' value return null; } diff --git a/src/main/java/com/xkrs/utils/CommonConstant.java b/src/main/java/com/xkrs/utils/CommonConstant.java index 21278b3..f73a62a 100644 --- a/src/main/java/com/xkrs/utils/CommonConstant.java +++ b/src/main/java/com/xkrs/utils/CommonConstant.java @@ -1,8 +1,5 @@ package com.xkrs.utils; -/** - * @author XinYi Song - */ public interface CommonConstant { /** diff --git a/src/main/java/com/xkrs/utils/DateTimeUtil.java b/src/main/java/com/xkrs/utils/DateTimeUtil.java index 6f14509..cb62e70 100644 --- a/src/main/java/com/xkrs/utils/DateTimeUtil.java +++ b/src/main/java/com/xkrs/utils/DateTimeUtil.java @@ -1,7 +1,6 @@ package com.xkrs.utils; import java.time.Instant; -import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; @@ -10,8 +9,6 @@ import java.util.regex.Pattern; /** * 日期时间工具 - * - * @author tajochen */ public class DateTimeUtil { @@ -21,41 +18,8 @@ public class DateTimeUtil { public final static DateTimeFormatter COMMON_FORMATTER_DATE = DateTimeFormatter.ofPattern(COMMON_PATTERN_DATE); public final static ZoneOffset DEFAULT_ZONE_OFFSET = ZoneOffset.of("+8"); - /** - * 字符串转LocalDate - * - * @param date - * @return - */ - public static LocalDate stringToDate(String date) { - LocalDate parse = null; - try { - parse = LocalDate.parse(date, COMMON_FORMATTER_DATE); - } catch (Exception e) { - e.printStackTrace(); - } - if (parse == null) { - return LocalDate.parse(date, COMMON_FORMATTER_DATETIME); - } - return parse; - } - - /** - * LocalDate转字符串 - * - * @param date - * @return - */ - public static String dateToString(LocalDate date) { - assert date != null; - return COMMON_FORMATTER_DATE.format(date); - } - /** * LocalDateTime转字符串 - * - * @param dateTime - * @return */ public static String dateTimeToString(LocalDateTime dateTime) { assert dateTime != null; @@ -64,9 +28,6 @@ public class DateTimeUtil { /** * 字符串转LocalDateTime - * - * @param date - * @return */ public static LocalDateTime stringToDateTime(String date) { LocalDateTime parse = null; @@ -81,159 +42,40 @@ public class DateTimeUtil { return parse; } - /** - * 字符串转Instant时间戳 - * - * @param str - * @return - */ - public static Instant stringToInstant(String str) { - assert str != null; - return stringToDateTime(str).toInstant(DEFAULT_ZONE_OFFSET); - } - - /** - * LocalDateTime转字符串(格式化) - * - * @param dateTime - * @param formatter - * @return - */ - public static String dateToStringFormatter(LocalDateTime dateTime, DateTimeFormatter formatter) { - assert dateTime != null; - return formatter.format(dateTime); - } - /** * 字符串转LocalDateTime(格式化) - * - * @param dateStr - * @param formatter - * @return */ public static LocalDateTime stringToDateTimeFormatter(String dateStr, DateTimeFormatter formatter) { assert dateStr != null; return LocalDateTime.parse(dateStr, formatter); } - /** - * 字符串转 local date - * - * @param dateStr - * @return - */ - public static LocalDate stringToDateFormatter(String dateStr) { - LocalDate date = LocalDate.parse(dateStr, COMMON_FORMATTER_DATE); - return date; - } - - - /** - * 日期转时间戳 - * - * @param dateTime - * @return - */ - public static long dateToTimeMillis(LocalDateTime dateTime) { - assert dateTime != null; - return dateTime.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli(); - } /** * 时间戳转日期 - * - * @param timeMillis - * @return */ public static LocalDateTime timeMillisToDate(long timeMillis) { Instant instant = Instant.ofEpochMilli(timeMillis); return LocalDateTime.ofInstant(instant, DEFAULT_ZONE_OFFSET); } - /** - * 时间戳转时间 - * - * @param timeMillis - * @return - */ - public static LocalDateTime timeMillisToTime(long timeMillis) { - LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(timeMillis, 0, ZoneOffset.ofHours(8)); - return localDateTime; - } - /** * 时间戳转时间再转字符串 - * - * @param timeMillis - * @return */ public static String timeMillisToString(long timeMillis) { LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(timeMillis, 0, ZoneOffset.ofHours(8)); return COMMON_FORMATTER_DATETIME.format(localDateTime); } - /** - * 获取当前时间 hh:mm:ss:nnn - * - * @return - */ - public static LocalDateTime getNowTime() { - LocalDateTime now = LocalDateTime.now(); - return now; - } - - /** - * 获取当前日期 yyyy-MM-dd - * - * @return - */ - public static LocalDate getToday() { - LocalDate now = LocalDate.now(); - return now; - } - - /** - * 获取当前 Instant 时间戳 - * - * @return - */ - public static Instant getInstant() { - Instant timeStamp = Instant.now(); - return timeStamp; - } - /** * 获取当前时间 yyyy-MM-ss hh:mm:ss - * - * @return */ public static String getNowTimeStr() { - return COMMON_FORMATTER_DATETIME.format(getNowTime()); - } - - /** - * 判断日期格式是否合法 "yyyy-MM-dd" - * - * @param strDate - * @return - */ - public static boolean isValidDate(String strDate) { - final int minLen = 10; - if (strDate == null || strDate.length() < minLen) { - return false; - } - //正则表达式校验日期格式 yyyy-MM-dd - String eL = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-" + "(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})" + "(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)(([0-9]{3}[1-9]|[0-9]{2}[1-9]" + "[0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-" + "(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|" + "((0[48]|[2468][048]|[3579][26])00))-02-29)"; - Pattern pat = Pattern.compile(eL); - Matcher matcher = pat.matcher(strDate); - return matcher.matches(); + return COMMON_FORMATTER_DATETIME.format(LocalDateTime.now()); } /** * 判断时间格式 格式必须为 "YYYY-MM-DD HH:mm:ss" - * - * @param sDateTime - * @return */ public static boolean isValidDateTime(String sDateTime) { final int minLen = 19; @@ -246,12 +88,4 @@ public class DateTimeUtil { return matcher.matches(); } - public static void main(String[] args) { - LocalDate now = LocalDate.now(); - LocalDate localDate = now.plusDays(1); - String s = dateToString(localDate); - LocalDate localDate1 = stringToDate(s); - System.out.println(localDate1); - } - } diff --git a/src/main/java/com/xkrs/utils/FileUtil.java b/src/main/java/com/xkrs/utils/FileUtil.java index 6a2d201..abaae00 100644 --- a/src/main/java/com/xkrs/utils/FileUtil.java +++ b/src/main/java/com/xkrs/utils/FileUtil.java @@ -80,40 +80,6 @@ public class FileUtil { return list; } - /** - * 移动文件到目标目录 - * @param path 文件路径 - * @return - */ - /*public static FileEntity mvFile(String path){ - String savePath = "D:" + File.separator + "dms" + File.separator + "data" ; - - File file = new File(path); - if (!file.isFile()) { - log.info("{}不是文件。",path); - return null; - } - // 从文件名获取到入库信息 暂时不知道 - String[] infos = path.split("/"); - String fileNameUnHandler = infos[infos.length - 1]; - String[] fileNameUnHandlerSplitWithPoint = fileNameUnHandler.split("."); - String fileName = fileNameUnHandlerSplitWithPoint[0]; - String scene = fileNameUnHandlerSplitWithPoint[1]; - String[] fileNames = fileNameUnHandler.split("_"); - long length = file.length(); - String filePath = File.separator + scene + File.separator + fileName; -// savePath = savePath + File.separator + dir + File.separator + fileName; - if (isFileExit(savePath + File.separator + scene)) { - if (file.renameTo(new File(filePath))) { - log.info("移动文件{}到{}目录",file.getName(), savePath + filePath); - } else { - log.info("文件{}移动失败",file.getName()); - return null; - } - } - return null; - }*/ - /** * 读取txt文件内容 * @param file diff --git a/src/main/java/com/xkrs/utils/FirePointCodeUtils.java b/src/main/java/com/xkrs/utils/FirePointCodeUtils.java index 3bad7a3..93dc54a 100644 --- a/src/main/java/com/xkrs/utils/FirePointCodeUtils.java +++ b/src/main/java/com/xkrs/utils/FirePointCodeUtils.java @@ -55,7 +55,7 @@ public class FirePointCodeUtils { continue; } LocalDateTime sysUserOverDateTime = DateTimeUtil.stringToDateTimeFormatter(sysUser.getOverTime(), DateTimeUtil.COMMON_FORMATTER_DATETIME); - if (sysUserOverDateTime.isBefore(DateTimeUtil.getNowTime())) { + if (sysUserOverDateTime.isBefore(LocalDateTime.now())) { if (!normalSmsEnable) {//根据配置信息决定普通用户是否发送短信 continue; } diff --git a/src/main/java/com/xkrs/utils/GaoDeApiUtil.java b/src/main/java/com/xkrs/utils/GaoDeApiUtil.java index a571f6d..7cd5294 100644 --- a/src/main/java/com/xkrs/utils/GaoDeApiUtil.java +++ b/src/main/java/com/xkrs/utils/GaoDeApiUtil.java @@ -55,13 +55,10 @@ public class GaoDeApiUtil { } public static void main(String[] args) { - List location = new ArrayList<>(); location.add("118.06454,37.8562"); GaoDeIgGeocodeVo geocode = geocode(location); System.out.println("sdfghjm"); - - } } diff --git a/src/main/java/com/xkrs/utils/HttpClientUtils.java b/src/main/java/com/xkrs/utils/HttpClientUtils.java index bc45351..491a3ef 100644 --- a/src/main/java/com/xkrs/utils/HttpClientUtils.java +++ b/src/main/java/com/xkrs/utils/HttpClientUtils.java @@ -55,8 +55,6 @@ public class HttpClientUtils { * @throws Exception */ public static String sendHttpsGet(String url) throws Exception { -// CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); - //CloseableHttpClient httpClient = HttpClients.createDefault(); SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); return doGet(url, httpClient); @@ -101,8 +99,6 @@ public class HttpClientUtils { * @throws Exception */ public static String sendHttpsPost(String url, String params) throws Exception { - // CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); - // CloseableHttpClient httpClient = null; SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); // CloseableHttpClient httpClient = HttpClients.createDefault(); diff --git a/src/main/java/com/xkrs/utils/IpUtil.java b/src/main/java/com/xkrs/utils/IpUtil.java deleted file mode 100644 index ef5bd73..0000000 --- a/src/main/java/com/xkrs/utils/IpUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.xkrs.utils; - -import javax.servlet.http.HttpServletRequest; - -/** - * IP地址处理工具 - * - * @author tajochen - */ -public class IpUtil { - - public static String getIpAddr(HttpServletRequest request) { - String ip = request.getHeader("x-forwarded-for"); - final String unkonwMsg = "unknown"; - final char splitChar = ','; - if (ip != null && ip.length() != 0 && !unkonwMsg.equalsIgnoreCase(ip)) { - // 多次反向代理后会有多个ip值,第一个ip才是真实ip - if (ip.indexOf(splitChar) != -1) { - ip = ip.split(",")[0]; - } - } - if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) { - ip = request.getHeader("Proxy-Client-IP"); - } - if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) { - ip = request.getHeader("WL-Proxy-Client-IP"); - } - if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) { - ip = request.getHeader("HTTP_CLIENT_IP"); - } - if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) { - ip = request.getHeader("HTTP_X_FORWARDED_FOR"); - } - if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) { - ip = request.getHeader("X-Real-IP"); - } - if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) { - ip = request.getRemoteAddr(); - } - System.out.println("获取客户端ip: " + ip); - return ip; - } -} diff --git a/src/main/java/com/xkrs/utils/RandomUtil.java b/src/main/java/com/xkrs/utils/RandomUtil.java index 6135ec2..3cfd163 100644 --- a/src/main/java/com/xkrs/utils/RandomUtil.java +++ b/src/main/java/com/xkrs/utils/RandomUtil.java @@ -4,8 +4,6 @@ import java.util.Random; /** * 随机字符串产生工具 - * - * @author tajochen */ public class RandomUtil { diff --git a/src/main/java/com/xkrs/utils/RequestUtil.java b/src/main/java/com/xkrs/utils/RequestUtil.java deleted file mode 100644 index f8eea50..0000000 --- a/src/main/java/com/xkrs/utils/RequestUtil.java +++ /dev/null @@ -1,260 +0,0 @@ -package com.xkrs.utils; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.xkrs.model.vo.FileServerResultVo; -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.util.*; - -/** - * 上传工具 - * @author tajochen - **/ -public class RequestUtil { - - /** - * 发送管理命令到文件服务器 - * @param url - * @param map - * @return - */ - public static FileServerResultVo postFileManage(String url, Map map){ - Logger log = LoggerFactory.getLogger(RequestUtil.class); - String body = ""; - // 创建httpclient对象 - CloseableHttpClient client = HttpClients.createDefault(); - // 创建post方式请求对象 - HttpPost httpPost = new HttpPost(url); - // 装填参数 - List nvps = new ArrayList(); - if(map!=null){ - for (Map.Entry entry : map.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - } - try { - // 设置参数到请求对象中 - httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); - // 设置header报文头信息 - httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); - httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0"); - httpPost.setHeader("Accept", "application"); - httpPost.setHeader("Accept-Encoding", "gzip, deflate"); - // 执行请求操作,并拿到结果(同步阻塞) - CloseableHttpResponse response = client.execute(httpPost); - // 获取结果实体 - HttpEntity entity = response.getEntity(); - if (entity != null) { - // 按指定编码转换结果实体为String类型 - body = EntityUtils.toString(entity, "UTF-8"); - } - EntityUtils.consume(entity); - // 释放链接 - response.close(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - client.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - FileServerResultVo fileServerResultVo = new FileServerResultVo(); - ObjectMapper mapper = new ObjectMapper(); - try { - fileServerResultVo = mapper.readValue(body, FileServerResultVo.class); - } catch (JsonProcessingException e) { - e.printStackTrace(); - log.warn(e.toString()); - - } - return fileServerResultVo; - } - - /** - * 模拟 get请求 - * @param url 链接 - * @param map 参数列表 - */ - public static void getStandard(String url, Map map) { - // 1.拿到一个httpclient的对象 - CloseableHttpClient httpClient = HttpClients.createDefault(); - // 2.设置请求方式和请求信息 - HttpPost httpPost = new HttpPost(url); - //2.1 提交header头信息 - httpPost.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"); - //2.1 提交请求体 - ArrayList parameters = new ArrayList(); - // 装填参数 - if(map!=null){ - for (Map.Entry entry : map.entrySet()) { - parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - } - - try { - httpPost.setEntity(new UrlEncodedFormEntity(parameters)); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - // 3.执行请求 - CloseableHttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (IOException e) { - e.printStackTrace(); - } - // 4.获取返回值 - String html = null; - try { - assert response != null; - html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } - // 5.打印 - System.out.println(html); - } - - /** - * 模拟Post请求 application/x-www-form-urlencoded - * @param url 资源地址 - * @param map 参数列表 - * @return - */ - public static String postStandard(String url, Map map) { - String body = ""; - // 创建httpclient对象 - CloseableHttpClient client = HttpClients.createDefault(); - // 创建post方式请求对象 - HttpPost httpPost = new HttpPost(url); - // 装填参数 - List nvps = new ArrayList(); - if(map!=null){ - for (Map.Entry entry : map.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - } - try { - // 设置参数到请求对象中 - httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); - // 设置header报文头信息 - httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); - httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0"); - httpPost.setHeader("Accept", "application"); - httpPost.setHeader("Accept-Encoding", "gzip, deflate"); - // 执行请求操作,并拿到结果(同步阻塞) - CloseableHttpResponse response = client.execute(httpPost); - // 获取结果实体 - HttpEntity entity = response.getEntity(); - if (entity != null) { - // 按指定编码转换结果实体为String类型 - body = EntityUtils.toString(entity, "UTF-8"); - } - EntityUtils.consume(entity); - // 释放链接 - response.close(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - client.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return body; - } - - /** - * 模拟Post请求 multipart/form-data - * @param postFile - * @param postUrl - * @param postParam - * @return - */ - public static Map postFile(File postFile,String postUrl,Map postParam) { - - Logger log = LoggerFactory.getLogger(RequestUtil.class); - Map resultMap = new HashMap(16); - CloseableHttpClient httpClient = HttpClients.createDefault(); - try{ - // 把一个普通参数和文件上传给下面这个地址 - HttpPost httpPost = new HttpPost(postUrl); - - // 设置传输参数 - MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); - // 解决乱码问题 - multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - multipartEntity.setCharset(StandardCharsets.UTF_8); - - // 设置文件参数 ,获取文件名postFile.getName() - // 把文件转换成流对象FileBody - multipartEntity.addBinaryBody("file",postFile, ContentType.create("multipart/form-data", Consts.UTF_8),postFile.getName()); - // 设计文件以外的参数 - Set keySet = postParam.keySet(); - for (String key : keySet) { - // 相当于 - multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("multipart/form-data", Consts.UTF_8))); - } - HttpEntity reqEntity = multipartEntity.build(); - httpPost.setEntity(reqEntity); - // 设置header报文头信息 - httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0"); - httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - httpPost.setHeader("Accept-Encoding","gzip, deflate"); - - // 发起请求,返回请求的响应 - CloseableHttpResponse response = httpClient.execute(httpPost); - try { - resultMap.put("statusCode", response.getStatusLine().getStatusCode()); - // 获取响应对象 - HttpEntity resEntity = response.getEntity(); - if (resEntity != null) { - // 打印响应内容 - resultMap.put("data", EntityUtils.toString(resEntity, StandardCharsets.UTF_8)); - resultMap.put("message", EntityUtils.toString(resEntity, StandardCharsets.UTF_8)); - resultMap.put("status", EntityUtils.toString(resEntity, StandardCharsets.UTF_8)); - } - // 销毁 - EntityUtils.consume(resEntity); - } catch (Exception e) { - e.printStackTrace(); - } finally { - response.close(); - } - } catch (IOException e1) { - e1.printStackTrace(); - } finally{ - try { - httpClient.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - log.info("上传结果:" + resultMap); - return resultMap; - } -} diff --git a/src/main/java/com/xkrs/utils/RestTemplateUtil.java b/src/main/java/com/xkrs/utils/RestTemplateUtil.java deleted file mode 100644 index dfb4384..0000000 --- a/src/main/java/com/xkrs/utils/RestTemplateUtil.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.xkrs.utils; - -import com.alibaba.fastjson.JSONObject; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -import javax.annotation.Resource; - -/** - * @author xkrs - */ -@Service -public class RestTemplateUtil { - - @Resource - private RestTemplate restTemplate; - - /** - * 以get方式请求第三方http接口 getForEntity - * @param url - * @return - */ - public JSONObject doGetForEntity(String url) { - ResponseEntity responseEntity = restTemplate.getForEntity(url, JSONObject.class); - return responseEntity.getBody(); - } - - /** - * 以get方式请求第三方http接口 getForObject - * 返回值返回的是响应体 - * @param url - * @return - */ - public JSONObject doGetForObject(String url) { - JSONObject result = restTemplate.getForObject(url, JSONObject.class); - return result; - } - - /** - * 以post方式请求第三方http接口 postForEntity - * @param url - * @return - */ - public JSONObject doPostForEntity(String url) { - //可设置请求参数 - JSONObject param = new JSONObject(); - param.put("userName","admin"); - param.put("ipAddress",""); - param.put("clientType","WINPC"); - ResponseEntity responseEntity = restTemplate.postForEntity(url, param, JSONObject.class); - return responseEntity.getBody(); - } - - /** - * 以post方式请求第三方http接口 postForObject - * @param url - * @return - */ - public JSONObject doPostForObject(String url,JSONObject param) { - JSONObject result = restTemplate.postForObject(url, param, JSONObject.class); - return result; - } - - - /** - * exchange方法请求第三方http接口 - * - */ - public JSONObject doExchange(String url, HttpHeaders httpHeaders, JSONObject param) { - //创建请求对象 - HttpEntity request = new HttpEntity<>(param,httpHeaders); - //执行请求(请求路径,请求方式,请求体,响应体) - ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class); - return responseEntity.getBody(); - } - - /** - * 发送第三方小米推送请求,向app端推送消息 - * @param url - * @param httpHeaders - * @param param - */ - public void doPostMessageToApp(String url,HttpHeaders httpHeaders,JSONObject param) { - //创建请求对象 - HttpEntity request = new HttpEntity<>(param,httpHeaders); - //执行请求(请求路径,请求方式,请求体,响应体) - restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class); - } - -} diff --git a/src/main/java/com/xkrs/utils/WDHttpClientUtils.java b/src/main/java/com/xkrs/utils/WDHttpClientUtils.java index 7773d98..35dd6c9 100644 --- a/src/main/java/com/xkrs/utils/WDHttpClientUtils.java +++ b/src/main/java/com/xkrs/utils/WDHttpClientUtils.java @@ -4,30 +4,13 @@ import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - /** * http工具类 */ @@ -47,21 +30,6 @@ public class WDHttpClientUtils { return doGet(url, httpClient); } - /** - * 发送https+get请求,绕过证书 - * - * @param url 请求地址 - * @return 返回结果 - * @throws Exception - */ - public static String sendHttpsGet(String url) throws Exception { -// CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); - //CloseableHttpClient httpClient = HttpClients.createDefault(); - SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); - return doGet(url, httpClient); - } - /** * 发送http+post请求 * @@ -87,24 +55,6 @@ public class WDHttpClientUtils { return doPost(httpClient, url); } - /** - * 发送https+post请求 - * - * @param url 请求地址 - * @param params 请求参数 json字符串 - * @return 返回结果 - * @throws Exception - */ - public static String sendHttpsPost(String url, String params) throws Exception { - // CloseableHttpClient httpClient = createIgnoreVerifyHttpClient(); - // CloseableHttpClient httpClient = null; - SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build(); - // CloseableHttpClient httpClient = HttpClients.createDefault(); - return doPost(httpClient, url, params); - - } - /** * 封装get请求方式的处理 */ @@ -166,37 +116,6 @@ public class WDHttpClientUtils { return result; } - /** - * 绕过验证 - * - * @return - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - */ - public static CloseableHttpClient createIgnoreVerifyHttpClient() throws Exception { - SSLContext sslContext = SSLContext.getInstance("TLS"); - // 实现一个X509TrustManager接口 - X509TrustManager trustManager = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - sslContext.init(null, new TrustManager[]{trustManager}, null); - Registry socketFactoryRegistry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext)).build(); - PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build(); - return httpClient; - } - } diff --git a/src/main/java/com/xkrs/utils/XlsxUtil.java b/src/main/java/com/xkrs/utils/XlsxUtil.java index 992d19e..a6836c0 100644 --- a/src/main/java/com/xkrs/utils/XlsxUtil.java +++ b/src/main/java/com/xkrs/utils/XlsxUtil.java @@ -134,7 +134,6 @@ public class XlsxUtil { } } - /** * 下载文件 单个 * @@ -149,4 +148,5 @@ public class XlsxUtil { e.printStackTrace(); } } + } diff --git a/src/main/java/com/xkrs/weather/service/impl/WeatherDataServiceImpl.java b/src/main/java/com/xkrs/weather/service/impl/WeatherDataServiceImpl.java index 40ee22e..1eed34f 100644 --- a/src/main/java/com/xkrs/weather/service/impl/WeatherDataServiceImpl.java +++ b/src/main/java/com/xkrs/weather/service/impl/WeatherDataServiceImpl.java @@ -26,7 +26,6 @@ public class WeatherDataServiceImpl implements WeatherDataService { return this.getWeatherResponse(uri); } - @Override public WeatherResponse getDataByCityName(String cityName) { String uri = WEATHER_URI + "city=" + cityName;