全网最快掌握Kotlin中使用Retrofit2简单实例

963 阅读2分钟

一、添加依赖项

    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")

二、创建数据类

// 登录前_接口_所需参数
data class LoginRequest(  
val password: String,  
val username: String  
)  

// 登录后_接口_返回参数
data class LoginResponse(  
val code: Int,  
val data: LoginRequest,  
val msg: String  
)

三、定义一个API接口

interface ApiService {
    /**
     * 登录
     */
    @POST("/api/v1/login") // 定义请求的API接口  
    fun login(@Body requset: LoginRequest): Call<LoginResponse>// 定义请求的方法
    
    // 2023-0823 补充上次疏漏的代码
    companion object {  
    // 创建一个Retrofit实例  
        fun create(context: Context): ApiService {  
            return ServiceCreator(context).create(ApiService::class.java)  
        }  
    }
}
/**
 * 我这里只用了一种,POST方式请求,参数使用@Body注解
 * 如果你的请求方式是其他或者需要更加详细的注解使用介绍
 * 请参考这篇文章:[Retrofit2 实战(一、使用详解篇) - 掘金 (juejin.cn)](https://juejin.cn/post/6978777076073660429#heading-4)
 */

Retrofit2 实战(一、使用详解篇) - 掘金 (juejin.cn)

四、定义一个Retrofit构造器

object ServiceCreator {
    // 接口地址 (换成你自己的接口地址)
    private const val BASE_URL = "https://xxx.baidu.com"  
    
    // 创建一个全局的Retrofit实例来实现代码复用,然后在需要的地方获取这个实例来创建ApiService。
    private val retrofit = Retrofit.Builder()  
    .baseUrl(BASE_URL)// 设置网络请求的Url地址  
    .addConverterFactory(GsonConverterFactory.create())// 设置数据解析器  
    .build()  
    // 创建实例
    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)  
}

五、同步方法请求

// 在携程内执行
CoroutineScope(Dispatchers.IO).launch {
   // 同步方法  
   // 创建 ApiService 实例  
   val apiService = ApiService.create()  
   // 创建请求体  
   val requset = LoginRequest("username123", "possword456")  
   // 发送请求  
   val response: Response<LoginResponse> = apiService.login(requset).awaitResponse()  
   if (response.isSuccessful) {  
       val res: LoginResponse? = response.body()!!  
       // 看控制台是否有结果
       Log.d("AppScreen", "onResponse: $res")  
   }
}

六、异步方法请求

// 在携程内执行
CoroutineScope(Dispatchers.IO).launch {
    // 异步方法  
    // 创建 ApiService 实例  
    val apiService2 = ApiService.create()  
    // 创建请求体  
    val requset2 = LoginRequest("username123", "possword456") 
    // 发送请求  
    apiService2.login(requset2).enqueue(object : Callback<LoginResponse> {
        // 请求成功响应
        override fun onResponse(  
        call: Call<LoginResponse>,  
        response: Response<LoginResponse>  
        ) {  
            if (response.isSuccessful) {  
            val res: LoginResponse? = response.body()!!  
            Log.d("AppScreen", "onResponse: $res")  
            }  
        }  
        
        // 请求失败或故障
        override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
            Log.d("AppScreen", "onFailure: $t")  
        }  
    })
}

七、后端接口返回参数

//返回数据给客户端
return {
    code: 200,
    data: {
        username,
        password
    },
    msg: "登录成功"
}

八、完整的代码


/**
 * 创建数据类
 */
// 登录前_接口_所需参数
data class LoginRequest(  
val password: String,  
val username: String  
)  

// 登录后_接口_返回参数
data class LoginResponse(  
val code: Int,  
val data: LoginRequest,  
val msg: String  
)

/**
 * 定义一个API接口
 */
 interface ApiService {
    /**
     * 登录
     */
    @POST("/api/v1/login") // 定义请求的API接口  
    fun login(@Body requset: LoginRequest): Call<LoginResponse>// 定义请求的方法
}

/**
 * 定义一个Retrofit构造器
 */
object ServiceCreator {
    // 接口地址
    private const val BASE_URL = "https://fc-mp-6b369ed8-6b37-4d6c-b0dc-baffe1a09079.next.bspapp.com"  
    
    // 创建一个全局的Retrofit实例来实现代码复用,然后在需要的地方获取这个实例来创建ApiService。
    private val retrofit = Retrofit.Builder()  
    .baseUrl(BASE_URL)// 设置网络请求的Url地址  
    .addConverterFactory(GsonConverterFactory.create())// 设置数据解析器  
    .build()  
    // 创建实例
    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)  
}

// TODO 在你需要的地方,调用下面两个方法测试

/**
 * 定义一个同步方法uLogin
 */
fun uLogin() {
    // 在携程内执行
    CoroutineScope(Dispatchers.IO).launch {
       // 同步方法  
       // 创建 ApiService 实例  
       val apiService = ApiService.create()  
       // 创建请求体  
       val requset = LoginRequest("username123", "possword456")  
       // 发送请求  
       val response: Response<LoginResponse> = apiService.login(requset).awaitResponse()  
       if (response.isSuccessful) {  
           val res: LoginResponse? = response.body()!!  
           // 看控制台是否有结果
           Log.d("AppScreen", "onResponse: $res")  
       }
    }
}

/**
 * 定义一个异步方法uLoginAsync
 */
fun uLoginAsync() {
    // 在携程内执行
    CoroutineScope(Dispatchers.IO).launch {
        // 异步方法  
        // 创建 ApiService 实例  
        val apiService2 = ApiService.create()  
        // 创建请求体  
        val requset2 = LoginRequest("username123", "possword456") 
        // 发送请求  
        apiService2.login(requset2).enqueue(object : Callback<LoginResponse> {
            // 请求成功响应
            override fun onResponse(  
            call: Call<LoginResponse>,  
            response: Response<LoginResponse>  
            ) {  
                if (response.isSuccessful) {  
                val res: LoginResponse? = response.body()!!  
                Log.d("AppScreen", "onResponse: $res")  
                }  
            }  

            // 请求失败或故障
            override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                Log.d("AppScreen", "onFailure: $t")  
            }  
        })
    }
}