当前位置:网站首页>Android实战开发-Kotlin教程(入门篇-登录功能实现 3.3)
Android实战开发-Kotlin教程(入门篇-登录功能实现 3.3)
2022-08-05 03:16:00 【南二爷】
上一篇我们利用前面学习的组件、布局知识成功的搭建一个登录界面,并且简单的实现了登录功能前的逻辑判断,今天我们来学习一下怎么具体的实现登录功能,具体来说,我们应该怎么样和服务端实现数据的请求和回调。
网络请求环境配置
Android的网络请求我们常用Retrofit+Okhttp的方式来请求接口。
首先,我们来配置一下依赖库,在我们Moudle项目的build.gradle文件新增依赖库。
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
第一个是retrofit的依赖包,第二个是okhttp框架包,通常会和第一个配合一起用,第三个是gson包,用来将json数据转换对应的实体对象或者列表。
其次,新建一个API配置接口文件命名ApiProtocol,用来查看和管理所有接口,内容格式如下:
interface ApiProtocol {
@POST("/smartbackstage/appUser/loginTest")
@FormUrlEncoded
fun submitLogin(@Field("userId") userId: String?,@Field("password") password: String?): Call<ResponseBody>
}
这里我们新增了一个submitLogin的接口,指定它的请求方式为Post请求,并且对应的服务端API为/smartbackstage/appUser/loginTest,同时指定两个请求参数分别为userId和password。
最后,我们需要在AndroidManifest.xml文件中新增网络请求权限。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.ktolin.application">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.KtolinApplication">
<activity
android:name=".LoginActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
登录请求
网络请求环境搭建完成后,我们来尝试一下完成登录模块的数据请求功能,在上一篇中我们完成了登录界面用户名和密码的简单的非空校验,完成校验后就可以将对应的值传入接口,下面我们创建一个登录请求方法。
private fun requestLogin(userId:String,password:String) {
val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.1.196:8443/") // 设置 网络请求 Url
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
.build()
val request = retrofit.create(ApiProtocol::class.java)
val call= request.submitLogin(userId,password)
call.enqueue(object :Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
println("请求成功")
val result = response.body().string()
System.out.println(result)
val entity:ResponseEntity= Gson().fromJson(result, ResponseEntity::class.java)
Toast.makeText(this@LoginActivity, "登录成功!", Toast.LENGTH_SHORT).show()
}
override fun onFailure(call: Call<ResponseBody>, throwable: Throwable) {
println("请求失败")
println(throwable.message)
}
})
}
这里baseUrl中需要填入对应的服务器主机地址,request.submitLogin(userId,password)指定接口请求成功后在onResponse方法中返回结果,请求失败后在onFailure中返回结果,请求成功后,我们需要将得到的结果转换为对应的实体对象。
请求结果:
{
"msg":"操作成功","code":200}
我们先创建一个实体对象结构,如下:
class ResponseEntity {
/*返回结果提示*/
var msg :String?=null
/*返回码*/
var code:Int=0
/*返回内容*/
var data=null
}
通过Gosn库我们可以将返回的Json格式结果转换为对应的实体类对象
val entity:ResponseEntity= Gson().fromJson(result, ResponseEntity::class.java)
至此,我们基本上实现了一个完整的登录模块。
边栏推荐
- 【Daily Training】1403. Minimum Subsequence in Non-Increasing Order
- Native js realizes the effect of selecting and canceling all the multi-select boxes
- MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现
- tree table lookup
- sql怎么找字段里所有数据为空的字段
- dmp(dump)转储文件
- 人人都在说的数据中台,你需要关注的核心特点是什么?
- 基于生长的棋盘格角点检测方法
- Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
- Common open source databases under Linux, how many do you know?
猜你喜欢
Beyond YOLO5-Face | YOLO-FaceV2 officially open source Trick+ academic point full
public static <T> List<T> asList(T... a) 原型是怎么回事?
The usage of try...catch and finally in js
Data to enhance Mixup principle and code reading
你要的七夕文案,已为您整理好!
【软件测试】自动化测试之unittest框架
Study Notes-----Left-biased Tree
How Jin Cang database correctness verification platform installation file
The Tanabata copywriting you want has been sorted out for you!
【已解决】Unity Coroutinue 协程未有效执行的问题
随机推荐
引领数字医学高地,中山医院探索打造未来医院“新范式”
627. Change of gender
[Solved] Unity Coroutine coroutine is not executed effectively
北斗三号短报文终端露天矿山高边坡监测方案
Apache DolphinScheduler, a new generation of distributed workflow task scheduling platform in practice - Medium
How Jin Cang database correctness verification platform installation file
Native js realizes the effect of selecting and canceling all the multi-select boxes
On governance and innovation, the 2022 OpenAtom Global Open Source Summit OpenAnolis sub-forum came to a successful conclusion
Intersection of Boolean Operations in SuperMap iDesktop.Net - Repairing Complex Models with Topological Errors
Chinese characters to Pinyin
mysql can't Execute, please solve it
Details such as compiling pretreatment
如何在WordPress中添加特定类别的小工具
人人都在说的数据中台,你需要关注的核心特点是什么?
Data to enhance Mixup principle and code reading
你要的七夕文案,已为您整理好!
Hash table lookup (hash table)
优炫数据库的单节点如何转集群
Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
沃谈小知识 |“远程透传”那点事儿