6.8 KiB
6.8 KiB
Retrofit原理
目录
Retrofit架构
架构图
┌─────────────┐
│ Interface │ ←─── API 接口定义
└──────┬──────┘
│
┌──────▼──────┐
│ Retrofit │ ←─── Retrofit 核心
└──────┬──────┘
│
┌──────┬──────┐
│ │ │
┌──────▼──────┐ ┌──────▼──────┐
│CallAdapter │ │Converter │
└──────┬──────┘ └──────┬──────┘
│ │
┌──────▼───────────────▼──────┐
│ OkHttp │ ←─── 底层 HTTP 客户端
└─────────────────────────────┘
核心组件
// Retrofit:核心类
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
// API 接口
public interface ApiService {
@GET("user/{id}")
Call<User> getUser(@Path("id") int id);
}
// 创建代理对象
ApiService api = retrofit.create(ApiService.class);
动态代理
代理模式
// Retrofit 使用动态代理创建 API 接口实现
// 1. 定义接口
public interface ApiService {
@GET("user/{id}")
Call<User> getUser(@Path("id") int id);
}
// 2. Retrofit 创建代理对象
ApiService api = retrofit.create(ApiService.class);
// 3. 调用方法时,代理对象拦截调用
// 4. 解析注解,构建 Request
// 5. 使用 OkHttp 执行请求
代理实现
// Retrofit 内部使用 Proxy.newProxyInstance 创建代理
ApiService api = (ApiService) Proxy.newProxyInstance(
ApiService.class.getClassLoader(),
new Class[]{ApiService.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
// 解析方法注解
// 构建 Request
// 执行请求
return null;
}
}
);
注解处理
请求方法注解
// @GET:GET 请求
@GET("user/{id}")
Call<User> getUser(@Path("id") int id);
// @POST:POST 请求
@POST("user")
Call<User> createUser(@Body User user);
// @PUT:PUT 请求
@PUT("user/{id}")
Call<User> updateUser(@Path("id") int id, @Body User user);
// @DELETE:DELETE 请求
@DELETE("user/{id}")
Call<Void> deleteUser(@Path("id") int id);
参数注解
// @Path:路径参数
@GET("user/{id}")
Call<User> getUser(@Path("id") int id);
// @Query:查询参数
@GET("user")
Call<List<User>> getUsers(@Query("page") int page, @Query("size") int size);
// @Body:请求体
@POST("user")
Call<User> createUser(@Body User user);
// @Header:请求头
@GET("user")
Call<User> getUser(@Header("Authorization") String token);
// @Field:表单字段
@POST("user")
@FormUrlEncoded
Call<User> createUser(@Field("name") String name, @Field("email") String email);
请求适配器
CallAdapter
// CallAdapter:将 Call 转换为其他类型
// 例如:RxJava、协程
// RxJava CallAdapter
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
// 使用
public interface ApiService {
@GET("user/{id}")
Observable<User> getUser(@Path("id") int id);
}
自定义 CallAdapter
// 自定义 CallAdapter
public class MyCallAdapterFactory extends CallAdapter.Factory {
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
// 返回自定义 CallAdapter
return new MyCallAdapter();
}
}
响应转换器
Converter
// Converter:将 ResponseBody 转换为对象
// 例如:Gson、Jackson
// Gson Converter
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.build();
// 使用
public interface ApiService {
@GET("user/{id}")
Call<User> getUser(@Path("id") int id);
// 自动将 JSON 转换为 User 对象
}
自定义 Converter
// 自定义 Converter
public class MyConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
// 返回自定义 Converter
return new MyConverter();
}
}
Retrofit与OkHttp
关系
// Retrofit 基于 OkHttp
// Retrofit 负责:
// 1. 接口定义和注解解析
// 2. 请求构建
// 3. 响应转换
// OkHttp 负责:
// 1. HTTP 请求执行
// 2. 连接管理
// 3. 拦截器处理
自定义 OkHttpClient
// 自定义 OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.connectTimeout(10, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(okHttpClient)
.build();
Retrofit源码分析
核心流程
// 1. 创建 Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.build();
// 2. 创建 API 接口代理
ApiService api = retrofit.create(ApiService.class);
// 3. 调用方法
Call<User> call = api.getUser(1);
// 4. 执行请求
Response<User> response = call.execute();
关键类
// Retrofit:核心类
// ServiceMethod:服务方法解析
// RequestFactory:请求构建工厂
// CallAdapter:请求适配器
// Converter:响应转换器
面试常见问题
Q1: Retrofit 的原理?
答案:
- 使用动态代理创建 API 接口实现
- 解析注解,构建 Request
- 使用 OkHttp 执行请求
- 使用 Converter 转换响应
Q2: Retrofit 和 OkHttp 的关系?
答案:
- Retrofit 基于 OkHttp
- Retrofit 负责接口定义和注解解析
- OkHttp 负责 HTTP 请求执行
Q3: Retrofit 的注解?
答案:
- 请求方法:@GET、@POST、@PUT、@DELETE
- 参数:@Path、@Query、@Body、@Header、@Field
Q4: Retrofit 的 CallAdapter 和 Converter?
答案:
- CallAdapter:将 Call 转换为其他类型(RxJava、协程)
- Converter:将 ResponseBody 转换为对象(Gson、Jackson)
最后更新:2024年