对于前端Android:
1.本例子采用的网络通信框架为OkHttp。
需要引入jar包为:implementation ‘com.squareup.okhttp3:okhttp:3.8.1’
2.解析JSON用的为Gson(当然可以采取自带的解析方式,Gson更为方便,且官方也推荐)
需要引入jar包为:implementation ‘com.google.code.gson:gson:2.8.5’
3.还需要添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
xml文件代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="50dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/et_userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名"
android:inputType="text"
android:maxLines="1"
android:singleLine="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"/>
<EditText
android:id="@+id/et_userPwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"/>
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="登 录"
android:textSize="18sp"
android:textColor="@color/white"
android:id="@+id/btn_login"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:background="@drawable/btn_bag"
android:foreground="?android:actionBarItemBackground"/>
</LinearLayout>
Java代码:
final EditText et_userName = findViewById(R.id.et_userName);
final EditText et_userPwd = findViewById(R.id.et_userPwd);
findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = et_userName.getText().toString();
String password = et_userPwd.getText().toString();
if(TextUtils.isEmpty(name)){
Toast.makeText(MainActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();
}else if(TextUtils.isEmpty(password)){
Toast.makeText(MainActivity.this,"密码不能为空",Toast.LENGTH_SHORT).show();
}else {
//初始化okhttp客户端
OkHttpClient client = new OkHttpClient.Builder().build();
//创建post表单,获取username和password(没有做非空判断)
RequestBody post = new FormBody.Builder()
.add("username",name)
.add("password",password)
.build();
//开始请求,填入url,和表单
final Request request = new Request.Builder()
//10.0.2.2为模拟机访问本地服务器需要填的ip地址,对于真机等情况可以看我之前的博客
.url("http://10.0.2.2/test3/api.php")
.post(post)
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
}
//获取成功
@Override
public void onResponse(okhttp3.Call call, final okhttp3.Response response) throws IOException {
//UI线程运行
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
//获取json
JSONObject jsonObject = new JSONObject(response.body().string());
//解析
BackCode backCode = new Gson().fromJson(jsonObject.toString(),BackCode.class);
//解析的结果
Log.i(TAG, "run: code:"+backCode.code);
Log.i(TAG, "run: massage:"+backCode.massage);
Log.i(TAG, "run: name:"+backCode.date.getName());
//分析结果
/*在这里判断成功的为 code = 1,失败为0,若有更多失败原因可以再添加message查看*/
if(backCode.code == 1) {
Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
}
});
数据类user:
public class user {
private String name;
private String age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(String age) {
this.age = age;
}
public String getAge() {
return age;
}
}
返回数据类BackCode:
public class BackCode {
public int code;
public String massage;
public user date;
}
至此android部分完成。
PHP部分
connect_config.php文件
<?php
// 服务器
define('DB_HOST', '127.0.0.1');
// 用户名
define('DB_USER', '填入你的用户名');
// 密码
define('DB_PWD', '填入密码');
// 数据库名
define('DB_NAME', '要选取数据库名称');
test_api.php文件
<?php
//加入文件
require_once 'connect_config.php';
//连接MySQl数据库
$conn = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME);
if(!$conn){
$data = array();
//链接数据库失败,虽然是失败,但还是依旧将返回的数据输出完整
$data['code'] = 2;
$data['massage'] = "连接数据库失败";
$data['date'] = array( "name"=>"","age"=>"");
//编译成json格式,最终会被android接受
echo json_encode($data,JSON_UNESCAPED_UNICODE);
}else{
$nickname = $_POST['username'];//必须与android写的post地方对应
$password = $_POST['password'];
//查询数据库
$query = "select * from user where UserName='$nickname' and Password='$password'";
$data1 = mysqli_query($conn, $query);
$row = mysqli_num_rows($data1);//返回的行数
$data = array();
if($row > 0){
$data["code"] = 1;
$data['massage'] = "登录成功";
$data['date'] = array( "name"=>"","age"=>"");
}else{
$data["code"] = 0;
$data['massage'] = "登录失败";
$data['date'] = array( "name"=>"","age"=>"");
}
echo json_encode($data,JSON_UNESCAPED_UNICODE);
//关闭数据库
mysqli_close($conn);
}
最终都全部完成,测试结果: