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)
}
相关推荐
我就是妖怪7 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
android·人工智能
心平气和量大福大8 小时前
android-实例-蒲公英-更新与安装-5-签名与生成APK
android·java·开发语言
阿pin9 小时前
Android随笔-Serializable与Parcelable
android·serializable·parcelable
天空之城--9 小时前
Android 事件分发机制深度解析——原理、源码与实战综合总结
android
阿pin10 小时前
Android随笔-AIDL
android·开发语言·aidl
2501_9160074711 小时前
Bundle ID 注册与管理 App ID 创建指南 命名规则 权限开关与删除注意事项
android·ios·小程序·https·uni-app·iphone·webview
雨白11 小时前
面向对象六大基本原则实战:从零重构支持引擎切换的网络框架
android·架构
张赐荣12 小时前
Android TalkBack 无障碍优化: 为控件自定义转子导航动作
android·microsoft
天空之城--14 小时前
Android Flutter行业动态与学习参考(2026年8月)
android·flutter
quantdash_cc15 小时前
基于 QuantDash 5 分钟 K 线的网格交易策略参数网格搜索寻优实战
android·开发语言·pandas·量化·quantdash