Android Retrofit使用记录

之前网络方面一直用的是Volley,但是近期发现Retrofit和Rxjava越来越火,抽时间学习了一下他们。

在此记录一下使用过程(分别从单纯利用Retrofit网络连接,以及Retrofit和Rxjava结合的请求)

(一)单独利用Retrofit 进行网络请求。

 首先放上build.gradle的依赖

  compile 'com.google.code.gson:gson:2.7'
  //rxjava
  compile 'com.squareup.retrofit2:retrofit-converters:2.1.0'
  compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
  compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
  compile 'com.github.bumptech.glide:glide:3.7.0'
  compile 'io.reactivex:rxandroid:1.2.1'
      在测试用例中用的是豆瓣的一个电影信息连接

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

   返回格式请自行查看。

(1)既然我们要请求数据,第一步肯定得有一个实体类:Movie

  public class Movie {
      public String getTitle() {
          return title;
      }
      public void setTitle(String title) {
          this.title = title;
      }
      public String getAlt() {
          return alt;
      }
      public void setAlt(String alt) {
          this.alt = alt;
      }
      String title;
      String alt;
}
(2)我们编写一个请求接口ApiService
  public interface ApiService {
      @GET("top250")
      Call<Movie> getMovieInfo(@Query("start")int start, @Query("count") int count);
  }

        解释:这里使用了注解

                 @GET 表示进行Get请求

                 @Query代表参数名 后面紧跟他的值

                 完整的请求就是     ......./top250?start=0&count=100

(3)准备工作完成,开始进行网络请求

  Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.douban.com/v2/movie/")
        .addConverterFactory(GsonConverterFactory.create())//添加 json 转换器
        .build();
  ApiService apiService = retrofit.create(ApiService.class);//这里采用的是Java的动态代理模式
  Call<Movie> call=apiService.getMovieInfo(0,10);
    call.enqueue(new Callback<Movie>() {
      @Override
      public void onResponse(Call<Movie> call, Response<Movie> response) {
          //do Something
        }
      @Override
      public void onFailure(Call<Movie> call, Throwable t) {
          //do Something
      }
});



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值