Retrofit2使用方式和源码解析

Retrofit2对Retrofit做了很大改进,做一下详细比对参考https://inthecheesefactory.com/blog/retrofit-2.0/en底层okhttp不同Retrofit 默认使用okhttpRetrofit2 默认使用okhttp3Service接口定义方式不同在Retrofit2之前如果定义一个同步的函数,应该这样定义:p
摘要由CSDN通过智能技术生成

简单介绍

Retrofit是一套RESTful架构的Android(Java)客户端实现,基于注解,提供JSON to POJO(Plain Ordinary Java Object,简单Java对象),POJO to JSON,网络请求(POST,GET,PUT,DELETE等)封装。

软件首页http://square.github.io/retrofit/

github地址https://github.com/square/retrofit

具体使用

官方文档非常清晰,Retrofit2对Retrofit做了很大改进,针对改进做一下分析和使用说明

底层okhttp不同

Retrofit 默认使用okhttp
Retrofit2 默认使用okhttp3

Service接口定义方式不同

在Retrofit2之前如果定义一个同步的函数,应该这样定义:
public interface GitHubService {
  
    @POST("/list")
    Repo loadRepo();
  
}
异步函数定义
public interface GitHubService {
  
    @POST("/list")
    void loadRepo(Callback<Repo> cb);
  
}
Retrofit2 同步异步方法定义一个接口就可以了
mport retrofit.Call;
public interface GitHubService {
  
    @POST("/list")
    Call<Repo> loadRepo();
  
}

如果要调用同步请求,只需调用execute;而发起一个异步请求则是调用enqueue。

Retrofit2 可以取消请求方法

Retrofit2请求使用Call,Call有cancel方法可以取消请求
只需调用call.cancel()就可以取消请求。

Converter现在从Retrofit2中删除,需要根据自己的需要引入Converter

这里是Square提供的官方Converter modules列表。选择一个最满足你需求的。
Gson: com.squareup.retrofit:converter-gson
Jackson: com.squareup.retrofit:converter-jackson
Moshi: com.squareup.retrofit:converter-moshi
Protobuf: com.squareup.retrofit:converter
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值