public interface MyInterface {
@GET(“…/…”)
Call<List<MyResponse>> getCall();
}
“…/…” 前面一部分是baseUrl地址,后面一部分是注解的那部分地址。注意:如果我们在注解后面参数已经设置一个完整的URL地址的话,那我们在设置Retrofit对象的时候可以不设置BaseUrl这个参数。
以下是 Retrofit.java 类中的代码:
// Single-interface proxy creation guarded by parameter safety.
@SuppressWarnings("unchecked")
public <T> T create(final Class<T> service) {
// 对传进来的接口字节码进行验证
Utils.validateServiceInterface(service);
// 标志位,表示是否需要提前验证和解析这个接口
if (validateEagerly) {
eagerlyValidateMethods(service);
}
// 使用的动态代理进行操作
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override // 真正解析接口操作的地方
public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
// 重要的三行代码
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall =
new OkHttpCall<>(serviceMethod, args);
return serviceMethod.adapt(okHttpCall);
}
});
}
boolean isDefaultMethod(Method method) {
return false;
}
ServiceMethod:对应一个接口的方法,它把它做好了封装,在这个里面大家以后会看到有众多的网络配置请求参数,还有包括URL等等。