MST

星途 面试题库

面试题:Kotlin中Retrofit网络请求基础配置

在Kotlin Android项目中,如何使用Retrofit进行基本的GET请求配置?请描述主要步骤,并给出关键代码示例。
27.6万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
  1. 添加依赖: 在build.gradle文件中添加Retrofit及相关依赖,示例如下:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  1. 定义API接口: 创建一个接口来定义你的GET请求。例如:
interface ApiService {
    @GET("your_endpoint")
    suspend fun getData(): Response<YourDataModel>
}

这里@GET注解指定了请求方法是GET,括号内为请求的端点;suspend关键字表示这是一个挂起函数,可以在协程中使用;Response<YourDataModel>表示返回的数据类型,YourDataModel需根据实际返回数据结构定义。 3. 创建Retrofit实例: 在需要发起请求的地方创建Retrofit实例,示例代码如下:

val retrofit = Retrofit.Builder()
   .baseUrl("https://your_base_url/")
   .addConverterFactory(GsonConverterFactory.create())
   .build()

这里baseUrl设置了请求的基础URL,addConverterFactory添加了Gson转换器用于解析返回的JSON数据。 4. 发起请求: 使用创建好的Retrofit实例创建API接口实例,并发起请求,示例代码如下:

val apiService = retrofit.create(ApiService::class.java)
CoroutineScope(Dispatchers.IO).launch {
    val response = apiService.getData()
    if (response.isSuccessful) {
        val data = response.body()
        // 处理数据
    } else {
        // 处理错误
    }
}

这里使用CoroutineScopeDispatchers.IO在IO线程中发起请求,以避免阻塞主线程。获取到响应后,通过isSuccessful判断请求是否成功,并处理响应数据或错误。