Kotlin使用Retrofit进行get请求的方法(懒加载机制)

185 阅读1分钟

添加依赖:

网络请求框架retrofit2和json解析框架converter-gson
compile ‘com.squareup.retrofit2:retrofit:2.1.0’
compile ‘com.squareup.retrofit2:converter-gson:2.1.0’

创建kotlin数据实体类

这里类的变量名和json中的key保持一致

/**
 * 数据类会默认重写toString和hashcode方法,显示类的变量值
 */
data class User(val login: String,val id:Long,val avatar_url:String)

网络请求方法和数据解析文件

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

interface GitHubService{//网络请求的接口,得到返回值list集合
    @GET("/repos/enbandari/Kotlin-Tutorials/stargazers")
    fun getStarGazers():Call<List<User>>
}
object Server{//单例模式
    val getHubService:GitHubService by lazy {
        Retrofit.Builder().baseUrl("https://api.github.com").addConverterFactory(GsonConverterFactory.create())
                .build().create(GitHubService::class.java)
    }
}

fun main(args: Array<String>) {
    Server.getHubService.getStarGazers().execute().body().map (::println)//此处打印user数据实体类,已经默认重写了toString方法,不会像java中那样打印实体类的地址,而是打印实体类的变量和变量值
}

运行结果:

这里写图片描述