Retrofit2.0的基本使用

时间:2020-12-04 16:07:16

前言:最近研究了一下时下最火的网络Http Client库,Retrofit2.0。因为之前一直没赶上1.0的趟,所以这次务必要快点上车啦。话不多说,直接开始!


特点:

1、性能好,处理快,使用简单

2、使用REST(REpresentational State Transfer,表述性状态转移) API,非常方便

3、支持NIO(NEW IO,主要作用就是用来解决速度差异的

4、默认使用OkHttp处理网络请求

5、默认使用Gson解析


前期准备:

选中我们的项目右击,选择Open Module Setttings,找到Dependencies,搜索关键字:retrofit2以及retrofit converter-gson。以目前最新的为例,我们需要添加如下代码:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
添加完成之后同步一下,这样我们前期的准备工作就已经完成了。

使用方法:

1、定义一个接口(封装URL地址和数据请求) 2、实例化一个Retrofit 3、通过Retrofit实例创建接口服务对象 4、接口服务对象调用接口中的方法,获得Call对象 5、Call对象执行请求(同步或者异步请求)

具体用法:

这里我们以糗事百科的api为例,做一个最简单的get请求。 首先我们需要定义一个baseUrl,做为我们的基本请求地址:
public class Api {
//baseurl
public final static String URL_BASE = "http://m2.qiushibaike.com";

//最新
public static final String URL_LATEST = "http://m2.qiushibaike.com/article/list/latest?page=%d";

}

再去定义一个ApiService接口
public interface ApiService {

@GET("article/list/latest?page=1")
Call<BeanList> getJsonString();
}

按照我们的使用方法,先创建一个Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.URL_BASE)
.addConverterFactory(GsonConverterFactory.create())//这里添加converterFactory是为了后面进行gson解析。
.build();

再通过Retrofit实例创建接口服务对象
ApiService apiService = retrofit.create(ApiService.class);

接口服务对象调用接口中的方法,获得Call对象,以及调用其中的请求方法
Call<BeanList> call = apiService.getJsonString();

利用call对象,执行同步或者异步请求。这里需要注意的是call对象有两种请求方式 call.execute()代表的是同步请求 call.enqueue()代表的是异步请求,返回的结果是在主线程中 我们以enqueue为例
call.enqueue(new Callback<BeanList>() {
@Override
public void onResponse(Call<BeanList> call, Response<BeanList> response) {
if (response.isSuccessful()) {
List<BeanList.Bean> beanList = response.body().getBeanList();

}
}

@Override
public void onFailure(Call<BeanList> call, Throwable t) {

}
});

到此,Retrofit的简单实用就完成了!