最近顶了几天前端,记录下知识点,
开发工具是hbuilderX,业务是根据app运行的设备信息来判断这个设备是否是已知设备库的设备,既此设备运行这个项目是否合法
思路就是项目启动时获取设备mac地址,IP地址,去设备库查询,如果没有就退出app,
第一步,uniapp获取设备mac地址
//获取mac地址 var net = plus.android.importClass("java.net.NetworkInterface") var wl0 = net.getByName(‘wlan0‘) var macByte = wl0.getHardwareAddress() var str = ‘‘ //下面这段代码来自网络 for (var i = 0; i < macByte.length; i++) { var tmp = ""; var num = macByte[i]; if (num < 0) { tmp =(255+num+1).toString(16); } else { tmp = num.toString(16); } if (tmp.length == 1) { tmp = "0" + tmp; } str += tmp; } console.log(str)
str既是我们的设备mac地址,需要注意的plus对象是在app启动的时候才监听,所以h5运行时是拿不到pius对象的,需要运行在手机上才可以,
第二步,拿到设备ip,
做这一步的时候我烦的要命,因为uniapp拿ip是真的难,最后忽然意识到我好像是个后端来着,请求的东西不都在request里面吗!
所以,前端传个mac地址完事,在接口里用request拿ip就简单多了,
public String validaSbip(String macdz,HttpServletRequest request){ //从请求中拿到客户端的IP地址 String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } System.out.println("IP地址:"+ip);//打印ip地址
然后就回到了我们前端的请求回调里写我们的验证就完事了
最后附上验证不通过时强制关闭APP
let p = result.data; if(p=="0"){//设备不存在 plus.runtime.quit(); //直接关闭项目 }else if(p=="-1"){//地址对,mac地址错误,关闭项目 plus.runtime.quit(); //直接关闭项目 }