栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android:Retrofit使用详解(超简单)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android:Retrofit使用详解(超简单)

前言

Retrofit设计思想:开发者不用关注网络通信的细节,只需要在接口文件中声明一系列方法和返回值,然后通过注解的方式指定该方法对应哪个服务器接口,以及需要提供哪些参数。当我们在程序中调用该方法时,Retrofit会自动向对应的服务器接口发起请求,并将响应的数据解析成返回值声明的类型。这就使得我们可以用更加面向对象的思维来进行网络操作。

1. 添加依赖项

在app下的build.gradle文件里添加

dependencies {
	implementation 'com.squareup.retrofit2:retrofit:2.9.0'  //Retrofit的依赖项
	implementation 'com.squareup.retrofit2:converter-gson:2.9.0'  //Retrofit-gson的依赖项
	......
}
2. 声明API服务接口
class Service {  //在Service类里定义,方便管理

    interface HotListService {

        @GET("get")
        fun getHotList(
            @Query("type") type: String,
            @Query("token") token: String
        ): Call

    }
    
}
3. 根据服务器回传JSON创建JAVA实体

JSON → JAVA 在线转换网址

public class HotListBean {  //

    private int code;
    private String msg;
    private Data data;
    private int time;
    private String log_id;

    public void setCode(int code){
        this.code = code;
    }
    public int getCode(){
        return this.code;
    }
    public void setMsg(String msg){
        this.msg = msg;
    }
    public String getMsg(){
        return this.msg;
    }
    public void setData(Data data){
        this.data = data;
    }
    public Data getData(){
        return this.data;
    }
    public void setTime(int time){
        this.time = time;
    }
    public int getTime(){
        return this.time;
    }
    public void setLog_id(String log_id){
        this.log_id = log_id;
    }
    public String getLog_id(){
        return this.log_id;
    }


    public static class Data {
        private String name;
        private String last_update;
        private List list;

        public void setName(String name){
            this.name = name;
        }
        public String getName(){
            return this.name;
        }
        public void setLast_update(String last_update){
            this.last_update = last_update;
        }
        public String getLast_update(){
            return this.last_update;
        }
        public void setList(List list){
            this.list = list;
        }
        public List getList(){
            return this.list;
        }
    }


    public static class News {
        private String title;
        private String link;
        private String other;

        public void setTitle(String title){
            this.title = title;
        }
        public String getTitle(){
            return this.title;
        }
        public void setLink(String link){
            this.link = link;
        }
        public String getLink(){
            return this.link;
        }
        public void setOther(String other){
            this.other = other;
        }
        public String getOther(){
            return this.other;
        }
    }

}
4. 创建Retrofit
class Utils {  //在常用工具类里定义,方便管理调用

    fun getRetrofit(baseUrl: String): Retrofit {
        
        val client = OkHttpClient.Builder()
            .connectTimeout(15000, TimeUnit.MILLISECONDS)  //预留足够时间连接服务器
            .readTimeout(15000, TimeUnit.MILLISECONDS)  //预留足够时间处理数据,否则偶尔出现超时java.net.SocketTimeoutException: timeout
            .build()
            
        val factory = GsonConverterFactory.create()
        
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client)
            .addConverterFactory(factory)
            .build()

    }
}
5. 使用Retrofit
class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
    }

    private fun initData() {
        getRetrofit("https://v2.alapi.cn/api/tophub/")  //获取Retrofit
            .create(HotListService::class.java)  //调用Service
            .getHotList("weibo", myToken)  //调用方法,Token需要自己获取
            .enqueue(object : Callback {
                override fun onResponse(call: Call, response: Response) {
                    Log.d("wdw", "get HotList success")
                    val body = response.body()  //获取response数据
                    val hotList = body?.data?.list  //获取hotList
                    recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)  //线性布局
                    recyclerView.adapter = MyAdapter(hotList) }  //将获取到的hotList显示在recyclerView
                }
                override fun onFailure(call: Call, t: Throwable) {
                    Log.d("wdw", "get HotList failed, $t")
                }
            })
    }
    
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/894574.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号