1.以前的项目没有网络框架,通常如下:

使用了Retrofit后的图片是这样的:

2.Retrofit代码实现:
A.Retrofit定义 RESTInterface相当于旧的Constants+praseJsonToObject
String baseUrl = "http://apis.juhe.cn/";
String ip ="112.112.11.11";
String key="224b189c4cdd14e9b112adcd77c51d2a";
interface RESTAPI{
@GET("ip/ipNew")
Call <Repo> get(@Query("ip") String ip, @Query("key") String key);
}
分析:
-
Retrofit 的注解@Get和@Post("xxx")里面 = Constants里面定义的service接口
-
Retrofit 的Call = praseJsonToObject 转换对象
这是种REST的定义标准
有兴趣的可以参考大神讲解阮一峰 RESTful API 设计指南
B.Retrofit 初始化
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
RESTAPI host = retrofit.create(RESTAPI.class);
分析
- Retrofit 初始化baseUrl
- Retrofit addConverterFactory 添加Gson转换器
C.Retrofit使用 call
Call call = host.get(ip, key);
Response<Repo> response = call.execute();
if (response != null && response.body() != null) {
System.out.println("Retrofit GET同步请求 >>> "
+ response.body().getResult().getCity()); }
分析
- Call<T> 里面的泛型就是可以适配自定义的返回对象Bean
- Retrofit 的返回值 response 使用后可以直接获取返回对象
遗留问题:
-
扩展问题: Retrofit 的BaseUrl初始化后是没办法修改的,只能初始化一次,难道要实例化多个Retrofit吗?这样不好管理。
-
深入问题:Retrofit 源码是如何实现封装的如:
- gson转换器是怎么实现的?
- REST接口的如何实例的?
- Retrofit的易用性是如何实现的?
参考: