导入retrofit
dependencies {
........
implementation("com.squareup.retrofit2:retrofit:3.0.0")
implementation("com.squareup.retrofit2:converter-gson:3.0.0")
}创建单例类
object servicecreator {
private const val base_url = "https://7a6396f8-09a1-4ade-b42a-f6db7776fb31.mock.pstmn.io"
private val retrofit = retrofit.builder()
.baseurl(base_url)
.addconverterfactory(gsonconverterfactory.create())
.build()
fun <t> create(serviceclass: class<t>): t = retrofit.create(serviceclass)
}创建数据类
数据格式
{
"data": [
{
"random": "3",
"def": "中止,停顿;归属待定,暂搁",
"word": "abeyance"
}
]
}data class wordlistbean(val data: list<wordbean>) data class wordbean(val random: string, val def: string, val word: string)
配置接口
interface appservice {
@get("/flutter")
fun getdata(): call<wordlistbean>
}调用网络接口
binding.clickbutc.setonclicklistener {
val appservice = servicecreator.create(appservice::class.java)
appservice.getdata().enqueue(object : callback<wordlistbean>{
override fun onresponse(call: call<wordlistbean?>, response: response<wordlistbean?>) {
log.d("clickactivity",response.body().tostring())
}
override fun onfailure(call: call<wordlistbean?>, t: throwable) {
log.d("clickactivity",t.tostring())
}
})
}打印结果
2025-11-15 01:07:28.592 23340-23340 clickactivity
com.bz.yh.xd.testkotlin
d wordlistbean(data=[wordbean(random=0, def=抛弃,遗弃;中止;陷入,沉湎于, word=abandon), wordbean(random=1, def=抛弃;放纵, word=abandonment), wordbean(random=2, def=缩略词,缩写形式;缩略, word=abbreviation), wordbean(random=3, def=中止,停顿;归属待定,暂搁, word=abeyance)])
使用实化来优化servicecreator
object servicecreator {
private const val base_url = "https://7a6396f8-09a1-4ade-b42a-f6db7776fb31.mock.pstmn.io"
private val retrofit = retrofit.builder()
.baseurl(base_url)
.addconverterfactory(gsonconverterfactory.create())
.build()
inline fun <reified t> create(): t = create(t::class.java)
} binding.clickbutc.setonclicklistener {
val appservice = servicecreator.create<appservice>()
appservice.getdata().enqueue(object : callback<wordlistbean>{
override fun onresponse(call: call<wordlistbean?>, response: response<wordlistbean?>) {
log.d("clickactivity",response.body().tostring())
}
override fun onfailure(call: call<wordlistbean?>, t: throwable) {
log.d("clickactivity",t.tostring())
}
})
}其他
声明网络权限
<uses-permission android:name="android.permission.internet" />
配置networksecurityconfig,使用http
<application
.....
android:networksecurityconfig="@xml/network_security_config">network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartexttrafficpermitted="true"/>
</network-security-config>到此这篇关于android开发(kotlin) retrofit基本使用的文章就介绍到这了,更多相关android kotin retrofit使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论