Retrofit解析
日期: 2019-04-08 分类: 个人收藏 336次阅读
@Retrofit 解析
解析的原因
我想给Service的每个body加上基本参数,如platform,version等
解析
我发现所有的service经过一个动态代理代理了所有方法,然后解析service方法的参数和返回值(获取参数的方式是通过反射方法的注解得到)。然后把参数作为okhttp的参数执行请求,请求回调中将结果解析成service方法的返回值,再通过rxjava的Observable传递给调用者。
核心代码解析
retrofit核心代码
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.callAdapter.adapt(okHttpCall);
}
});
}
解析结果
我成功的把每个body添加了基本参数
我把body都继承自BaseBody,然后重写GsonRequestBodyConverter
/**
* Created by antelope on 2017/12/6.
*/
public class MyGsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
private String version;
public MyGsonRequestBodyConverter<T> setVersion(String version) {
this.version = version;
return this;
}
public MyGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
try {
value.getClass().getMethod("setPlatform", String.class).invoke(value, "01");
if (version != null) {
value.getClass().getMethod("setVersion", String.class).invoke(value, version);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
标签:Android Java
上一篇: 秩与线性方程组的解的关系
精华推荐