Retrofit的使用基本步骤

Retrofit

https://gank.io/post/56e80c2c677659311bed9841

Retorfit是一个对http请求封装的开源库,与volley相似,但是工作原理不同。

  • volley是通过创建request然后将其添加进RequestQueue然后由Dispatcher分发处理的。
  • 而Retrofit是通过接口与代理方法实现Request请求,由于其个部分的灵活性,还可以与RxJava组合使用,十分便捷。

    1. Retrofit的使用方法。

例如对豆瓣电影TOP250进行请求:

https://api.douban.com/v2/movie/top250?start=0&count=10

  • 首先需要创建一个借口,有关于请求的接口:
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使用的基本步骤。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值