Android登录实例

最近实现了一个极简的app登录功能,验证身份是通过向http服务器传url参数实现的

这次写代码,也并不顺利,经过不断尝试修改代码,最后才完成

代码实现的功能极其简陋,我觉得以后那天再回来看这篇文章的代码一定会被鞭尸

我还是想记录下,这种不断试错的精神,我认为是成为一个好的开发者的品质,需要发扬

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity {
TextView et1,et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(TextView)this.findViewById(R.id.et1);
et2=(TextView)this.findViewById(R.id.et2);

Button bt1=(Button)this.findViewById(R.id.bt1);
Button bt2=(Button)this.findViewById(R.id.bt2);
}
public void register(View view){
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
public void sign(View view) {
String ac = et1.getText().toString();
String pw = et2.getText().toString();
Log.e("账号", ac);
Log.e("密码", pw);
if (!ac.equals("") && !pw.equals("")) {
// Toast.makeText(getApplication(),"用户名密码正常",Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
String ac = et1.getText().toString();
String pw = et2.getText().toString();
Log.e("账号", ac);
Log.e("密码", pw);
String str = "http://www.tomatobz.xyz:3000/login?Accout=" + ac + "&Password=" + pw;
URL url = new URL(str);
Log.e("url", str);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
InputStream inputStream = httpURLConnection.getInputStream();
InputStream in = url.openStream();//url非常重要的方法 openStream()返回输入流 用于读取网页流内容
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
String result = "";
while ((line = br.readLine()) != null) {
result += line;
Log.e("返回结果", result);
}
if (result.equals("success")) {
//通知主线程更新
makeToastByHandlerSendMessage("登录成功");
Intent intent = new Intent(MainActivity.this, home.class);
startActivity(intent);
} else {
//通知主线程更新
makeToastByHandlerSendMessage("账号或密码出错");
}
br.reset();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
else{
Toast.makeText(getApplication(),"用户名或密码不能为空",Toast.LENGTH_SHORT).show();
}
}


static final int SUCCESS=1;
static final int FAIL=0;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SUCCESS:
Toast.makeText(MainActivity.this, msg.getData().get("msg").toString(), Toast.LENGTH_SHORT).show();
break;
case FAIL:
Toast.makeText(MainActivity.this, msg.getData().get("msg").toString(), Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
};

private void makeToastByHandlerSendMessage(String msgStr) {
Message msg = new Message();
msg.what = 0;
Bundle bundle = new Bundle();
bundle.putString("msg", msgStr);
msg.setData(bundle);
handler.sendMessage(msg);
}
}

RegisterActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inspector.StaticInspectionCompanionProvider;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RegisterActivity extends AppCompatActivity {
EditText username,password1,password2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username=(EditText)this.findViewById(R.id.register1);
password1=(EditText)this.findViewById(R.id.register2);
password2=(EditText)this.findViewById(R.id.register3);
Button bt1=(Button)this.findViewById(R.id.registerbt);
}
public void register(View view) {
String ac = username.getText().toString();
String pwd1 = password1.getText().toString();
String pwd2 = password2.getText().toString();
Log.e("验证账号",ac);

Log.e("验证两次密码是否一致",pwd1+" "+pwd2);
if(pwd1.equals(pwd2)&&!pwd1.equals("")&&!pwd2.equals("")){
//Toast.makeText(getApplication(),"密码一致",Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
String ac=username.getText().toString();
String pw=password1.getText().toString();
String str="http://www.tomatobz.xyz:3000/register?Accout="+ac+"&Password="+pw;
URL url = new URL(str);
Log.e("url",str);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
InputStream in=url.openStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
//将输入流封装成 BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String result=sb.toString();
if (result.equals("success")){
//通知主线程更新
makeToastByHandlerSendMessage("注册成功");
Intent intent = new Intent(RegisterActivity.this, home.class);
startActivity(intent);
}else{
//通知主线程更新
makeToastByHandlerSendMessage("账号重复,换个账号吧");
}
br.reset();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}else{
Toast.makeText(getApplication(), "密码不一致,请重新输入", Toast.LENGTH_SHORT).show();
}
}



static final int SUCCESS=1;
static final int FAIL=0;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SUCCESS:
Toast.makeText(RegisterActivity.this, msg.getData().get("msg").toString(), Toast.LENGTH_SHORT).show();
break;
case FAIL:
Toast.makeText(RegisterActivity.this, msg.getData().get("msg").toString(), Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
};

private void makeToastByHandlerSendMessage(String msgStr) {
Message msg = new Message();
msg.what = 0;
Bundle bundle = new Bundle();
bundle.putString("msg", msgStr);
msg.setData(bundle);
handler.sendMessage(msg);
}
}

node服务器上的监听代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const express = require('express')
let dbmodule = require('./sql.js')
const app = express()
const port = 3000

//建立链接
dbmodule.connect((err) => {
if (err) {
console.log(err)
console.log('数据库连接失败')
} else {
console.log('数据库连接成功')
app.get('/login', function(req, res) {
var accout = req.query.Accout
var pwd = req.query.Password
console.log(accout)
console.log(pwd)
var sql = 'select * from user where Accout = ? and Password = ? '
dbmodule.query(sql, [accout, pwd], function(err, fields) {
//console.log(res)
console.log(fields)
res.send(JSON.stringify(fields) === '[]' ? "err" : "success")
})
})
app.get('/register', function(req, res) {
var accout = req.query.Accout
var pwd = req.query.Password
var sql1 = 'select * from user where Accout=?'
var sql2 = 'insert into user(Accout,Password) values(?,?)'
dbmodule.query(sql1, [accout], function(err, fields) {
if (JSON.stringify(fields) === '[]') {
dbmodule.query(sql2, [accout, pwd], (err, r) => {
console.log(r)
res.send("success")
})
} else {
res.send("err")
}
})
})
app.listen(port, () => console.log(`Server running at http://127.0.0.1:${port}`))
}
})

功能

  • 实现登录功能,输入登录用户名和密码,当输入用户名或密码为空时,跳出提示,账号或密码不为空,前端就终止了下一步访问接口,防止用户误点
  • 如果登录的账号密码和数据库的密码不匹配,就会提示出错
  • 当输入正确的用户名和密码后,跳转到正常主页面
  • 若注册时输入的密码不一致,会提示不一致
  • 若注册的账号,服务器数据库中没有,则添加数据,跳转到组页面,注册成功

问题

问题呢,很多,比如安全的问题,密码是绝对不能以明文的方式出现在url中的,再不济写个通过post传递,都要好;还有代码复用的问题,不够简洁;以后肯定会被当成垃圾代码

界面