之前在公司遇到过一个问题,软件是有使用时间限制的,如何避免用户修改系统时间的漏洞继续使用软件
可以从网络获取网络时间和系统时间做比对,判断当前系统时间是否正确,可以通过自己的需求进行编写
获取网络时间代码如下:
try {
// 创建URL对象
URL url = new URL("https://www.baidu.com");
// 打开连接
URLConnection conn = url.openConnection();
// 获取服务器时间戳 注:断网情况下获取到的网络时间戳为0
long serverTime = conn.getDate();
// 转换为日期对象
Date date = new Date(serverTime);
// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String networkDate = sdf.format(date);
String systemDate = sdf.format(new Date());
// 输出结果
System.out.println("网络时间:" + networkDate);
System.out.println("系统时间:" + systemDate);
} catch (Exception e) {
e.printStackTrace();
}