OkHttp实现登录注册验证
首先,添加OkHttp依赖
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
因为静态接口需要Java8才能支持使用,我们要使用静态接口,需要在build.gradle文件中添加如下配置声明,使用Java8编译
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
不然会出现如下异常:
错误一:
Static interface methods are only supported starting with Android N (--min-api 24): java.util.List okhttp3.Dns.lambda$static$0(java.lang.String) Message{kind=ERROR, text=Static interface methods are only supported starting with Android N (--min-api 24):
java.util.List okhttp3.Dns.lambda$static$0(java.lang.String),sources=[Unknown source file], tool name=Optional.of(D8)}
错误二:
Invoke-customs are only supported starting with Android O (--min-api 26)
Message{kind=ERROR, text=Invoke-customs are only supported starting with Android O (--min-api 26), sources=[Unknown source file], tool name=Optional.of(D8)}
在AndroidManifest.xml中添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
创建OkHttpTools工具类:
1 public class OkHttpTools { 2 //创建OkHttpClient对象 3 private final OkHttpClient client = new OkHttpClient(); 4 //登录验证的方法 5 public String Login(String username,String password){ 6 //创建请求体并传递参数 7 RequestBody formBody = new FormBody.Builder() 8 .add("username",username) 9 .add("password",password) 10 .build(); 11 //创建Request对象 12 Request request = new Request.Builder() 13 .url("http://192.168.*.*:8080/LoginUser") 14 .post(formBody) 15 .build(); 16 //获取Response对象 17 try (Response response = client.newCall(request).execute()) { 18 //响应成功并返回响应内容 19 if (response.isSuccessful()) { 20 return response.body().string(); 21 //此时代码执行在子线程,修改UI的操作使用handler跳转到UI线程 22 } 23 }catch (Exception e){ 24 e.printStackTrace(); 25 } 26 //响应失败返回" " 27 return " "; 28 } 29 //注册验证的方法 30 public String Register(String username,String password){ 31 RequestBody formBody = new FormBody.Builder() 32 .add("username",username) 33 .add("password",password) 34 .build(); 35 Request request = new Request.Builder() 36 .url("http://192.168.*.*:8080/RegisterUser") 37 .post(formBody) 38 .build(); 39 40 try (Response response = client.newCall(request).execute()) { 41 if (response.isSuccessful()) { 42 return response.body().string(); 43 } 44 }catch (Exception e){ 45 e.printStackTrace(); 46 } 47 return " "; 48 }
49 }
LoginActivity中
1. 获取响应内容并进行验证:
1 // 登录按钮的点击事件 2 btn_login.setOnClickListener(new View.OnClickListener() { 3 @Override 4 public void onClick(View v) { 5 //获取界面的控件 6 getEditString(); 7 //控件的密码进行加密 8 String md5Psw = MD5Utils.md5(psw); 9 //从SharedPreferences中根据用户名获取密码 10 spPsw = readSpw(userName); 11 if (TextUtils.isEmpty(userName)) { 12 Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show(); 13 return; 14 } else if (TextUtils.isEmpty(psw)) { 15 Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show(); 16 return; 17 } else if (true) { 18 //创建子线程并获取数据 19 new Thread() { 20 @Override 21 public void run() { 22 OkHttpTools tools = new OkHttpTools(); 23 String flag=""; 24 //传递参数获取响应内容 25 String result = tools.Login(userName, psw); 26 //判断数据库查询出来值是否与输入的值相等 27 if (result.equals(userName+psw)){ 28 flag="success"; 29 } 30 if (flag.equals("success")) { 31 handler.sendEmptyMessage(MSG_SUCCESS); 32 } else { 33 handler.sendEmptyMessage(MSG_FAIL); 34 } 35 } 36 }.start(); 37 return; 38 } else if (!TextUtils.isEmpty(spPsw) && !md5Psw.equals(spPsw)) { 39 Toast.makeText(LoginActivity.this, "输入的用户名和密码不一致", Toast.LENGTH_SHORT).show(); 40 return; 41 } else { 42 Toast.makeText(LoginActivity.this, "此用户名不存在", Toast.LENGTH_SHORT).show(); 43 return; 44 } 45 } 46 });
2. Handler接收子线程中的验证消息并进行处理:
1 //界面上显示数据 2 Handler handler = new Handler() { 3 @Override 4 public void handleMessage(Message msg) { 5 if (msg.what == MSG_SUCCESS) { 6 Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); 7 //保存登录的状态和用户名 8 saveLoginStatus(true, userName); 9 //登录成功的状态保存到MainActivity 10 Intent intent = new Intent(); 11 intent.putExtra("isLogin", true); 12 setResult(RESULT_OK, intent); 13 LoginActivity.this.finish(); 14 }else { 15 Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show(); 16 } 17 } 18 };
RegisterActivity中
1. 获取响应内容并进行验证:
1 //注册按钮的点击事件 2 btn_register.setOnClickListener(new View.OnClickListener() { 3 @Override 4 public void onClick(View v) { 5 //获取输入到控件的值 6 getEditString(); 7 if (TextUtils.isEmpty(userName)) { 8 Toast.makeText(RegisterActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show(); 9 return; 10 } else if (TextUtils.isEmpty(psw)) { 11 Toast.makeText(RegisterActivity.this, "请输入密码", Toast.LENGTH_SHORT).show(); 12 return; 13 } else if (TextUtils.isEmpty(pswAgain)) { 14 Toast.makeText(RegisterActivity.this, "请输入确认密码", Toast.LENGTH_SHORT).show(); 15 return; 16 } else if (!psw.equals(pswAgain)) { 17 Toast.makeText(RegisterActivity.this, "确认密码和密码不一致", Toast.LENGTH_SHORT).show(); 18 return; 19 } else { 20 new Thread() { 21 @Override 22 public void run() { 23 OkHttpTools tools = new OkHttpTools(); 24 String result = tools.Register(userName, psw); 25 if (result.equals("success")) { 26 handler.sendEmptyMessage(MSG_SUCCESS); 27 } else if (result.equals(userName)) { 28 handler.sendEmptyMessage(MSG_REPEAT); 29 } else { 30 handler.sendEmptyMessage(MSG_FAIL); 31 } 32 } 33 }.start(); 34 return; 35 } 36 } 37 });
2. Handler接收子线程中的验证消息并进行处理:
1 Handler handler = new Handler() { 2 @Override 3 public void handleMessage(Message msg) { 4 if (msg.what == MSG_SUCCESS) { 5 Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show(); 6 //把用户名和密码保存到SharedPreferences中 7 saveRegisterInfo(userName, psw); 8 //把注册成功的用户名传到LoginActivity 9 Intent data = new Intent(); 10 //要传的用户名 11 data.putExtra("userName", userName); 12 setResult(RESULT_OK, data); 13 RegisterActivity.this.finish(); 14 } else if (msg.what == MSG_REPEAT) { 15 Toast.makeText(RegisterActivity.this, "此用户名已存在", Toast.LENGTH_SHORT).show(); 16 } else { 17 Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show(); 18 } 19 } 20 };
Web项目中获取请求,进行数据处理并返回响应结果:
UserController:
1 @Controller 2 public class UserController { 3 //注入userService 4 @Autowired 5 private UserService userService; 6 //处理用户登录的方法 7 @RequestMapping("/LoginUser") 8 public void LoginUser(HttpServletRequest request,HttpServletResponse response) throws IOException { 9 //设置响应编码 10 response.setCharacterEncoding("UTF-8"); 11 PrintWriter out = response.getWriter(); 12 //获取请求的用户名和密码 13 String username = request.getParameter("username"); 14 String password = request.getParameter("password"); 15 //对用户名和密码进行拼接 16 String user= username+password; 17 //从数据库中获取全部数据 18 List<User> users = userService.findUsers(); 19 //存放从数据库中获取的全部数据 20 List<String> userList = new ArrayList<>(); 21 for (User u:users){ 22 String info = u.getUsername()+u.getPassword(); 23 userList.add(info); 24 } 25 //判断集合中是否含有获取的数据 26 if (userList.contains(user)){ 27 System.out.println("true"); 28 out.write(user); 29 }else { 30 System.out.println("false"); 31 out.write("fail"); 32 } 33 34 } 35 //处理用户注册的方法 36 @RequestMapping("/RegisterUser") 37 public void RegisterUser(HttpServletRequest request,HttpServletResponse response) throws IOException { 38 //设置响应编码 39 response.setCharacterEncoding("UTF-8"); 40 PrintWriter out = response.getWriter(); 41 //获取请求信息 42 String username = request.getParameter("username"); 43 String password = request.getParameter("password"); 44 //进行注册之前先判断数据库中是否含有该用户名 45 //查询全部信息并把信息添加到集合中,以备验证用户名是否存在 46 List<User> users = userService.findUsers(); 47 List<String> userList = new ArrayList<>(); 48 for (User u:users){ 49 String name = u.getUsername(); 50 userList.add(name); 51 } 52 //判断是否含有该用户 53 if (!userList.contains(username)){ 54 //不含有该用户名向数据库中添加信息 55 User user = new User(); 56 user.setUsername(username); 57 user.setPassword(Integer.parseInt(password)); 58 //向数据库中插入数据 59 int row = userService.insertUser(user); 60 if (row>0){ 61 out.write("success"); 62 }else { 63 System.out.println("信息添加失败"); 64 out.write("fail"); 65 } 66 }else if (userList.contains(username)){ 67 //含有该用户名把用户名返回 68 out.write(username); 69 }else { 70 out.write("fail"); 71 } 72 } 73 } 74