Retrofit
Retorfit是一个对http请求封装的开源库,与volley相似,但是工作原理不同。
- volley是通过创建request然后将其添加进RequestQueue然后由Dispatcher分发处理的。
而Retrofit是通过接口与代理方法实现Request请求,由于其个部分的灵活性,还可以与RxJava组合使用,十分便捷。
- Retrofit的使用方法。
例如对豆瓣电影TOP250进行请求:
- 首先需要创建一个借口,有关于请求的接口:
public interface MovieService {
@GET("top250")
Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
}
- 其次是具体的请求与处理返回结果
private void getMovie(){
String baseUrl = "https://api.douban.com/v2/movie/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
MovieService movieService = retrofit.create(MovieService.class);
Call<MovieEntity> call = movieService.getTopMovie(0, 10);
call.enqueue(new Callback<MovieEntity>() {
@Override
public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
resultTV.setText(response.body().toString());
}
@Override
public void onFailure(Call<MovieEntity> call, Throwable t) {
resultTV.setText(t.getMessage());
}
});
}
- 这里可以看到这样一句代码:
MovieService movieService = retrofit.create(MovieService.class);
这句代码是Retrofit中精妙的处理,使用了Java中动态代理机制,看上去好像是create了一个MovieService本身实际上是创建了一个MovieService的代理,从Retrofit的源码中可以看出:
/** Create an implementation of the API defined by the {@code service} interface. */
@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, 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);
}
return loadMethodHandler(method).invoke(args);
}
});
}
可以看到,定义的请求借口对象被转换成了它的代理对象,使用代理对象而不是委托对象。这里就是使用到了Java中的动态代理的方法,一方面确保了原始对象的安全性,一方面增强了灵活性。
Call<MovieEntity> call = movieService.getTopMovie(0, 10);
这条语句实际上是调用了movieService代理对象的getTopMovie()方法,并且根据方法参数类型与接口定义的将其装配称为Http请求,之后只需要调用call.excute() 或者 call.enqueue()便可以将请求发出,其中,excute()是同步请求,enqueue()是异步请求。之后在回调CallBack对返回结果进行解析。
以上就是Retrofit使用的基本步骤。