1. 前言:
- 为了方便,将注册页面和登录页面也在一块。演示:
2.数据库搭建:MySQL
create database test;
use test;
create table user(
user_id int primary key auto_increment,
user_name varchar(10) not null unique,
user_passwd varchar(10) not null);
3.服务端开发:PHP
3.1编写数据库连接函数:
<?php
$databaseConnection = null;
// 创建一个获取连接函数,用于访问要访问服务器上的数据库
function getConnection(){
$hostname = "localhost"; //数据库服务器的主机名,可以使用IP
$database = "test";
$userName = "root";
$password = "";
global $databaseConnection;
$databaseConnection = @mysql_connect($hostname, $userName, $password) or die(mysql_error());
mysql_query("set names 'utf-8'");
@mysql_select_db($database, $databaseConnection) or die(mysql_error());
}
// 创建一个关闭函数,用于断开与数据库的连接
function closeConnection(){
global $databaseConnection;
if($databaseConnection){
mysql_close($databaseConnection) or die(mysql_error());
}
}
?>
3.2用户注册:
<?php
session_start(); //启动PHP会话
$response = array(); //定义JSON响应数组
include_once ("conn.php"); //连接数据库
getConnection();
//判断是否获取到所需的输入
if(isset($_POST['user_name']) && isset($_POST['user_passwd'])){
$user_name = $_POST['user_name'];
$user_passwd = $_POST['user_passwd'];
// 判断用户名是否占用
$userNameSQL = "select * from user where user_name = '$user_name'";
$resultSet = mysql_query($userNameSQL);
if(mysql_num_rows($resultSet)>0){
$response["success"] = 0;
$response["message"] = "Name is used";
// 返回JSON响应
echo json_encode($response);
closeConnection();
exit();
}
//数据库插入
$result = mysql_query("insert into user(user_name, user_passwd)
values('$user_name', '$user_passwd')");
//判断插入是否成功
if($result){
// success
$response["success"] = 1;
$response["message"] = "Successfully created.";
echo json_encode($response);
} else{
// fail
$response["success"] = 0;
$response["message"] = "An error occurred.";
echo json_encode($response);
}
} else{
// not input
$response["success"] = 0;
$response["message"] = "Required fields is missing.";
echo json_encode($response);
}
closeConnection();
?>
3.3用户登录:
<?php
session_start();
$response = array();
include_once("conn.php");
getConnection();
//判断是否获取到非空的输入
if(isset($_POST['user_name']) && isset($_POST['user_passwd'])){
$user_name = $_POST['user_name'];
$user_passwd = $_POST['user_passwd'];
//判断用户名是否登记,且判断密码
$userNameSQL = "select * from user
where user_name = '$user_name'
and user_passwd = '$user_passwd'";
$resultSet = mysql_query($userNameSQL);
if(mysql_num_rows($resultSet) > 0){
$user = mysql_fetch_array($resultSet);
$_SESSION['user_name'] = $user['user_name'];
$_SESSION['user_passwd'] = $user['user_passwd'];
$response['success'] = 1;
$response["message"] = "Welcome login";
echo json_encode($response);
} else{
$response['success'] = 0;
$response["message"] = "Wrong user name or password";
echo json_encode($response);
}
}
closeConnection();
?>
4. Android客户端开发:
4.1 登录页面:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
tools:context="com.example.study.MainActivity" >
<!--账号-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
>
<TextView
android:layout_width="34dp"
android:layout_height="30dp"
android:text="账号:"
android:layout_marginRight="10dp"
/>
<EditText
android:id="@+id/user_name"
android:layout_width="match_parent"
android:layout_height="48dp"
android:hint="请输入账号"
/>
</LinearLayout>
<!--密码-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="horizontal"
android:layout_marginBottom="10dp"
>
<TextView
android:layout_width="34dp"
android:layout_height="30dp"
android:text="密码:"
android:layout_marginRight="10dp"
/>
<EditText
android:id="@+id/user_passwd"
android:layout_width="match_parent"
android:layout_height="48dp"
android:hint="请输入密码"
/>
</LinearLayout>
<Button
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:background="#FBE201"
/>
<Button
android:id="@+id/register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册账号"
android:background="@null"
android:textColor="#159DFF"
android:layout_gravity="right"
/>
</LinearLayout>
4.2 服务器访问类:JSONParser.java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONParser {
static InputStream is = null; // JSON输入流
static String json = ""; // 将JSON输入流转换为字符串
public JSONParser(){
}
//通过HTTP POST方式连接指定的URL
public String makeHttpRequest(String url_string, String method, String param){
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(url_string);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
//用输出流向服务器发出参数,要求字符,所有不能直接用getOutputStream
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(param);
dos.flush();
dos.close();
if(connection.getResponseCode() == 200){ // 返回200表示响应成功
is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
}catch (Exception e){
e.printStackTrace();
}
return json;
}
}
4.3 MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity{
private Button loginBtn;
private Button registerBtn;
private EditText usernameEdit, userpwdEdit;
JSONParser jsonParser = new JSONParser();
private String jsonData; // 服务器返回值
private String message; // 服务器返回值
private int success; //服务器返回值
public static String user_name;
/**
* BaseURL需要改成你们要访问的ip的地址。
* 如果是在模拟器上使用,要写10.0.2.2,写localhost会被认为是模拟器本身。
* 如果是在手机上使用,手机和电脑要在同一局域网,ip地址使用电脑的ipv4,可以在命令行输出ipconfig查看。
*/
private static String BaseURL = "http://10.0.2.2/test/";
//注册地址
private static String url_register = BaseURL + "register.php";
//登录地址
private static String url_login = BaseURL + "login.php";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//控件
loginBtn = findViewById(R.id.login_button);
registerBtn = findViewById(R.id.register_button);
usernameEdit = findViewById(R.id.user_name);
userpwdEdit = findViewById(R.id.user_passwd);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(usernameEdit.getText().toString().equals("")
|| userpwdEdit.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),
"请输入账号密码", Toast.LENGTH_SHORT).show();
} else{
new Login().execute();
}
}
});
// 为了方便,注册页面就不写了,和 登录页面 写在一起
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(usernameEdit.getText().toString().equals("")
|| userpwdEdit.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),
"请输入账号密码", Toast.LENGTH_SHORT).show();
} else{
new Register().execute();
}
}
});
}
/**
* 注册的后台异步任务
*/
class Register extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
// 可以在此添加显示一个环形进度条
}
/**
* 开始执行后台异步任务
*/
protected String doInBackground(String... args){
String url = url_register;
String name = usernameEdit.getText().toString();
String passwd = userpwdEdit.getText().toString();
try{
// 使用GET方法,是在URL中发送的。
// 使用POST方法,是在POST请求的HTTP消息主题中发送的。
String param = "user_name=" + URLEncoder.encode(name, "UTF-8")
+ "&user_passwd=" + URLEncoder.encode(passwd, "UTF-8");
jsonData = jsonParser.makeHttpRequest(url, "POST", param);
JSONObject jsonObject = new JSONObject(jsonData);
message = jsonObject.getString("message");
success = jsonObject.getInt("success");
} catch (Exception e){
Log.e("log_tag :", e.toString());
}
return null;
}
/**
* 异步任务完成后给出提示信息
*/
protected void onPostExecute(String file_url){
String str = "" + success;
Toast.makeText(getApplicationContext(),
"返回码=" + str + " : " + message, Toast.LENGTH_SHORT).show();
}
}
/**
* 登录的后台异步任务
*/
class Login extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* 开始执行后台异步任务
*/
protected String doInBackground(String... args){
String url = url_login;
String name = usernameEdit.getText().toString();
String passwd = userpwdEdit.getText().toString();
try{
String param = "user_name=" + URLEncoder.encode(name, "UTF-8")
+ "&user_passwd=" + URLEncoder.encode(passwd, "UTF-8");
jsonData = jsonParser.makeHttpRequest(url, "POST", param);
JSONObject jsonObject = new JSONObject(jsonData);
message = jsonObject.getString("message");
success = jsonObject.getInt("success");
} catch (Exception e){
Log.e("log_tag :", e.toString());
}
return null;
}
/**
* 异步任务完成后给出提示信息
*/
protected void onPostExecute(String file_url){
String str = "" + success;
if(success == 1){
Toast.makeText(getApplicationContext(),
"登录成功", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(),
"返回码=" + str + " : " + message, Toast.LENGTH_SHORT).show();
}
}
}
}