IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android客户端与服务端交互实现简单的登录功能 -> 正文阅读

[移动开发]Android客户端与服务端交互实现简单的登录功能

实现思路:

安卓客户端输入账号和密码,使用 okHttp 向服务器端发送请求并传递输入的账号和密码,服务器端的登录接口查询数据库,判断是否能登录成功,然后返回给客户端JSON字符串,客户端使用Gson解析服务器返回的数据,做出不同的操作。这里仅展示一个很简单的例子。

服务端:

1. 数据库

2. web服务

服务端 Java Web 用SpringBoot+Mybatis-Plus 快速搭建的,接口返回如下 map 集合:

    if(users.size() != 0){
        map.put("msg","登录成功");
    }else {
        map.put("msg","账号或密码错误");
    }
    return map;
复制代码

重点是在安卓端

安卓端:

1. 登录页面xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textUsername"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:text="账号:"
        app:layout_constraintBottom_toBottomOf="@+id/editUsername"
        app:layout_constraintEnd_toStartOf="@+id/editUsername"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/editUsername" />

    <TextView
        android:id="@+id/textPassword"
        android:layout_width="wrap_content"
        android:layout_height="23dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:text="密码:"
        app:layout_constraintBottom_toBottomOf="@+id/editPassword"
        app:layout_constraintEnd_toStartOf="@+id/editPassword"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/editPassword" />

    <EditText
        android:id="@+id/editUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="23dp"
        android:layout_marginRight="23dp"
        android:ems="10"
        android:hint="请输入用户名/手机号"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textUsername"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:layout_marginEnd="23dp"
        android:layout_marginRight="23dp"
        android:ems="10"
        android:hint="请输入密码"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textPassword"
        app:layout_constraintTop_toBottomOf="@+id/editUsername" />

    <Button
        android:id="@+id/login"
        android:layout_width="142dp"
        android:layout_height="42dp"
        android:layout_marginStart="200dp"
        android:layout_marginLeft="200dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="57dp"
        android:layout_marginRight="57dp"
        android:text="登录"
        app:layout_constraintEnd_toEndOf="@+id/editPassword"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>
复制代码

2. MainActivity.java

public class MainActivity extends AppCompatActivity {

    private EditText editUsername;
    private EditText editPassword;
    //服务器端的登录接口
    private String url = "http://192.168.17.xx:8081/user/login";
    private String address = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取用户输入的数据
        editUsername = findViewById(R.id.editUsername);
        editPassword = findViewById(R.id.editPassword);
        Button login = findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editUsername.getText().toString();
                String password = editPassword.getText().toString();
                //向服务器传参
                address = url+"?username="+username+"&password="+password;
                login();

            }
        });
    }

    //登录操作中开启一个子线程
    private void login(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.sendOkHttpRequest(address);
                    if(response != null){
                        String responseData = response.body().string();
                        Map<String,Object> map = null;
                        //使用Gson解析服务器返回的数据
                        Gson gson = new Gson();
                        Type type = new TypeToken<Map<String,Object>>(){}.getType();
                        map = gson.fromJson(responseData,type);
                        String msg = map.get("msg").toString();
                        //判断登录成功还是失败,并向主线程传递数据
                        if("登录成功".equals(msg)){
                            Message message = new Message();
                            message.what = 1;
                            message.obj = msg;
                            handler.sendMessage(message);
                        }else{
                            Message message = new Message();
                            message.what = 2;
                            message.obj = msg;
                            handler.sendMessage(message);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //根据子线程传来数据的不同,进行不同的操作
    Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case 1:
                    String data = (String) msg.obj;
                    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                    intent.putExtra("msg",data);
                    startActivity(intent);
                    break;
                case 2:
                    String data2 = (String) msg.obj;
                    Toast.makeText(MainActivity.this, data2, Toast.LENGTH_SHORT).show();
            }
        }
    };

}
复制代码

其中 String url = "http://192.168.17.99:8081/user/login" 是服务端的登录接口,

SecondActivity 就是打开一个空白的页面activity_second.xml,就不粘代码了,

HttpUtil 是用的 OkHttp。

public class HttpUtil {
    public static Response sendOkHttpRequest(String address) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
复制代码

3. 运行

最后运行服务器端代码,让手机和服务器端处于同一网络,就能测试登录了。

4. 注意

okhttp 和 gson 依赖应该添加好:

implementation 'com.squareup.okhttp3:okhttp:4.2.2'
implementation 'com.google.code.gson:gson:2.7'

AndroidManifest.xml 打开权限

android:usesCleartextTraffic="true" //使用明文传输

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-07-15 16:18:51  更:2021-07-15 16:20:01 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/6 8:45:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码