Android retrofit使用模板

1,加入网络访问权限

复制代码
<uses-permission android:name="android.permission.INTERNET" />

2,引入依赖

复制代码
implementation "com.google.code.gson:gson:2.8.5"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"

3,实体类

复制代码
data class Banner(
    val desc: String,
    val id: Int,
    val imagePath: String,
    val isVisible: Int,
    val order: Int,
    val title: String,
    val type: Int,
    val url: String
)

4,模板返回体

data class BaseResponse<T>( val data: T, val errorCode: Int, val errorMsg: String )

5,API类

复制代码
import retrofit2.Call
import retrofit2.http.GET

interface WanAndroidApi {
    @GET("banner/json")
    fun getBanners(): Call<BaseResponse<List<Banner>>>
}

6,工具类

复制代码
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object NetworkUtil {
    private val retrofit: Retrofit =
        Retrofit.Builder()
            .baseUrl("https://www.wanandroid.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

    val wanAndroidApi:WanAndroidApi = retrofit.create(WanAndroidApi::class.java)
}
相关推荐
tianshi48519 分钟前
Android 应用启动窗口(Splash Screen)的创建与销毁流程
android
脚踏实地,坚持不懈!26 分钟前
ICU Calendar 实际工作问题排查手册
android
ii_best1 小时前
安卓脚本/ios开发软件按键精灵实战:自动定位弹窗广告关闭按钮坐标的通用方案
android·ios·自动化
天空之城--1 小时前
Android Jetpack Compose 状态管理浅析
android·android jetpack
企业数字化笔记5 小时前
固定资产财务账与实物账怎么对账?折旧快照、差异检测与SQL核对
android·数据库·sql
千里马-horse7 小时前
第 66 章:在 Android 上运行 Windows 游戏
android·aosp
云边有个稻草人11 小时前
飞牛 NAS 远程访问实战:星空组网连接 Mac 与安卓,从 Compose 部署到 5G 验证
android·5g·macos
聚美智数11 小时前
手机号归属地-手机号归属地查询-手机归属地-运营商归属地
android·智能手机
恋猫de小郭11 小时前
Shopify 从 React Native 回到 Swift/Kotlin,但是你以为有手就行??
android·前端·ios
菠萝加点糖11 小时前
Android ChipGroup 使用说明
android