前言
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<HotListBean>
}
}
3. 根据服务器回传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<News> 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<News> list){
this.list = list;
}
public List<News> 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<HotListBean> {
override fun onResponse(call: Call<HotListBean>, response: Response<HotListBean>) {
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<HotListBean>, t: Throwable) {
Log.d("wdw", "get HotList failed, $t")
}
})
}
}