当前位置:网站首页>Android Practical Development - Kotlin Tutorial (Introduction - Login Function Implementation 3.3)
Android Practical Development - Kotlin Tutorial (Introduction - Login Function Implementation 3.3)
2022-08-05 03:20:00 【Second Master Nan】
In the previous article we used the components we learned earlier、Layout knowledge successfully builds a login interface,And it simply implements the logical judgment before the login function,Today we will learn how to implement the login function in detail,具体来说,How should we implement data requests and callbacks with the server.
Network request environment configuration
AndroidThe network requests we commonly useRetrofit+Okhttpway to request the interface.
首先,Let's configure the dependency library,在我们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框架包,Usually used in conjunction with the first one,第三个是gson包,用来将jsonThe entity object or list corresponding to the data conversion.
其次,新建一个APIConfiguration interface file namingApiProtocol,Used to view and manage all interfaces,内容格式如下:
interface ApiProtocol {
@POST("/smartbackstage/appUser/loginTest")
@FormUrlEncoded
fun submitLogin(@Field("userId") userId: String?,@Field("password") password: String?): Call<ResponseBody>
}
这里我们新增了一个submitLogin的接口,Specify its request method as Post请求,and the corresponding serverAPI为/smartbackstage/appUser/loginTest,Specify two request parameters at the same timeuserId和password.
最后,我们需要在AndroidManifest.xmlAdded network request permission to the file.
<?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>
登录请求
After the network request environment is set up,Let's try to complete the data request function of the login module,In the previous article, we completed a simple non-null verification of the login interface username and password,After the verification is completed, the corresponding value can be passed into the interface,Next we create a login request method.
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)
}
})
}
这里baseUrlYou need to fill in the corresponding server host address,request.submitLogin(userId,password)After the specified interface request is successfulonResponse方法中返回结果,After the request failsonFailure中返回结果,请求成功后,We need to convert the obtained result to the corresponding entity object.
请求结果:
{
"msg":"操作成功","code":200}
We start by creating an entity object structure,如下:
class ResponseEntity {
/*返回结果提示*/
var msg :String?=null
/*返回码*/
var code:Int=0
/*返回内容*/
var data=null
}
通过Gosnlibrary we can returnJsonThe format result is converted to the corresponding entity class object
val entity:ResponseEntity= Gson().fromJson(result, ResponseEntity::class.java)
至此,We basically implemented a complete login module.
边栏推荐
- YYGH-13-客服中心
- private package
- Beyond YOLO5-Face | YOLO-FaceV2 officially open source Trick+ academic point full
- mysql can't Execute, please solve it
- The pit of std::string::find return value
- How to sort multiple fields and multiple values in sql statement
- 高项 02 信息系统项目管理基础
- QT: The Magical QVarient
- 2022 High-level installation, maintenance, and removal of exam questions mock exam question bank and online mock exam
- ffmpeg -sources分析
猜你喜欢
![Tencent Cloud [Hiflow] New Era Automation Tool](/img/ac/5c61424f22cd9fed74dcd529fdb6a4.png)
Tencent Cloud [Hiflow] New Era Automation Tool

YYGH-13-Customer Service Center

MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现

Beidou no. 3 short message terminal high slope in open-pit mine monitoring programme

QT language file production

使用二维码传输文件的小工具 - QFileTrans 1.2.0.1

毕设-基于SSM房屋租赁管理系统

Leading the highland of digital medicine, Zhongshan Hospital explores to create a "new paradigm" for future hospitals

龙蜥社区第二届理事大会圆满召开!理事换届选举、4 位特约顾问加入

Details such as compiling pretreatment
随机推荐
Burp installation and proxy settings
sql server 安装提示用户名不存在
In 2022, you still can't "low code"?Data science can also play with Low-Code!
Android实战开发-Kotlin教程(入门篇-登录功能实现 3.3)
How to transfer a single node of Youxuan database to a cluster
Call Alibaba Cloud oss and sms services
(十一)元类
MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现
Study Notes-----Left-biased Tree
1667. Fix names in tables
静态方法获取配置文件数据
Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
sql server installation prompts that the username does not exist
rpc-remote procedure call demo
2022高处安装、维护、拆除考试题模拟考试题库及在线模拟考试
ffmpeg -sources分析
Is your data safe in this hyperconnected world?
Question about #sql shell#, how to solve it?
mysql can't Execute, please solve it
rpc-remote procedure call demo