面试题答案
一键面试- 添加依赖:
在
build.gradle
文件中添加Retrofit及相关依赖,示例如下:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
- 定义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 {
// 处理错误
}
}
这里使用CoroutineScope
和Dispatchers.IO
在IO线程中发起请求,以避免阻塞主线程。获取到响应后,通过isSuccessful
判断请求是否成功,并处理响应数据或错误。