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)
}
相关推荐
奥尔特星云大使14 小时前
MySQL 慢查询日志slow query log
android·数据库·mysql·adb·慢日志·slow query log
2501_9159184118 小时前
iOS 框架全解析,原生框架与跨平台框架对比、开发应用打包与 App Store 上架实战经验
android·ios·小程序·https·uni-app·iphone·webview
K24B;19 小时前
多模态大语言模型LISA++
android·人工智能·语言模型·分割·多模态大语言模型
molihuan1 天前
开源 全平台 哔哩哔哩缓存视频合并 Github地址:https://github.com/molihuan/hlbmerge_flutter
android·flutter·缓存·ffmpeg·开源·github·音视频
奶糖 肥晨1 天前
批量重命名技巧:使用PowerShell一键整理图片文件命名规范
android·服务器·数据库
Momentary_SixthSense1 天前
如何对较长的Stream链进行Debug
android·java·开发语言
little_fat_sheep1 天前
【Rive】rive-android源码分析
android
教程分享大师1 天前
新魔百和m401h全部版本当贝桌面固件卡刷包和线刷包带adb权限
android
rufeii1 天前
网鼎杯 2020 青龙组
android
我要升天!1 天前
MySQL表的内连和外连
android·mysql·adb