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

来源:互联网 发布:云图制作软件 编辑:程序博客网 时间:2024/06/05 05:29

    • 添加依赖
    • 创建kotlin数据实体类
    • 网络请求方法和数据解析文件
    • 运行结果

添加依赖:

网络请求框架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.Callimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryimport retrofit2.http.GETinterface 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中那样打印实体类的地址,而是打印实体类的变量和变量值}

运行结果:

这里写图片描述

阅读全文
0 0
原创粉丝点击