What is Retrofit
官网如是说:Retrofit turns your HTTP API into a Java interface;
Github上这样介绍:Type-safe HTTP client for Android and Java。
Why Retrofit
- 类型安全
- 方便OkHttp的使用
How Retrofit Works
- 使用
-
将HTTP api转成Java接口
private interface WeatherService { @GET("weatherApi?") Call<Gson> getWeatherByCity(@Query("city") String cityName) }
-
构建Retrofit
Retrofit.Builder builder = new Retrofit.Builder(); Retrofit retrofit = builder.client(new OkHttpClient()) .baseUrl("https://www.apiopen.top/") .addConverterFactory(GsonConverterFactory.create()) .build();
-
用Retrofit创建Java接口实例
WeatherService weatherService = retrofit.create(WeatherService.class);
-
然后我们就可以通过调用这个接口里面的方法间接地调用HTTP接口了
-
同步式
retrofit2.Response<Gson> response = weatherService.getWeatherByCity("北京").execute();
-
异步式
weatherService.getWeatherByCity(new String("北京".getBytes("UTF-8"))) .enqueue(new Callback<Gson>() { @Override public void onResponse(Call<Gson> call, Response<Gson> response) { System.out.println("response == " + response.toString()); } @Override public void onFailure(Call<Gson> call, Throwable t) { t.printStackTrace(); } });
-
-
-
- 原理
- 接口实例如何创建的
- 很显然这是用动态代理模式创建的
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. 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); } }); }
- 很显然这是用动态代理模式创建的
- 一个普通的接口方法WeatherService如何能执行一个HTTP请求?
Request toRequest(@Nullable Object... args) throws IOException { }
可以看到1中代理方法里面有一个ServiceMethod,这个类的toRequest方法使用WeatherService接口方法的注解参数构造一个Http Request。
-
得到Request之后,通过OkHttpCall创建一个Call
private okhttp3.Call createRawCall() throws IOException { Request request = serviceMethod.toRequest(args); okhttp3.Call call = serviceMethod.callFactory.newCall(request); if (call == null) { throw new NullPointerException("Call.Factory returned null."); } return call; }
可以看到,这个Call就是OkHttp里面的类,说明Retrofit底层用的就是OkHttp
-
然后OkHttpCall对这个call做了什么呢?
@Override public synchronized Request request() { okhttp3.Call call = rawCall; if (call != null) { return call.request(); } if (creationFailure != null) { if (creationFailure instanceof IOException) { throw new RuntimeException("Unable to create request.", creationFailure); } else { throw (RuntimeException) creationFailure; } } try { return (rawCall = createRawCall()).request(); } catch (RuntimeException e) { creationFailure = e; throw e; } catch (IOException e) { creationFailure = e; throw new RuntimeException("Unable to create request.", e); } }
可以看到这个call调用了其request()方法,这其实就是通过OkHttp创建了一个Request对象。
-
OkHttpCall 和 ExecutorCallback都实现了Call的接口,那么这两个类的作用有什么区别?
// 暂时先分析到这,未完待续。太累了,先休息下。 -
- 接口实例如何创建的