深入理解android使用Retrofit

1 Retrofit介绍

Retrofit是square开源的网络Restful请求框架,底层是基于okhttp的,使用起来有点像feign,写后台的朋友应该会比较熟悉,看了Retrofit的源码会发现实现原理和feign一样,都是基于Java的动态代理来实现的,开发者只需要定义接口就可以了,Retrofit提供了注解可以表示该接口请求的请求方式、参数、url等。定义好了接口以后,在调用该远程接口的时候直接使用该接口就好像通过RPC方式使用本地类一样方便。这对于后续的代码维护是很大的便利,不用每次再去查看url才知道这个调用是干嘛的,接口的上送参数和返回也不用再去查看接口文档,这些信息在接口中都定义好了。对于不熟悉动态代理的同学可以看下这篇文章 http://www.jianshu.com/p/3a429c787a52

下面我们先简单说下使用Retrofit的基本流程,这里我们使用github的接口来试验:

gradle中引入retrofit

    compile 'com.squareup.retrofit2:retrofit:2.3.0'

接口定义

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

创建Retrofit实例和服务接口,在创建远程接口的时候必须要使用Retrofit接口来create接口的动态代理实例。Retrofit实例可以通过Builder去创建,在Builder过程中可以定义baseUrl,还可以定义json解析的工厂类,还可以定义RxJava的CallAdapter类,这些后面会详细讲解。

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

接口调用,接口调用比较简单,直接调用定义的接口函数就可以了,默认的返回值是Call<T>类型。

Call<List<Repo>> repos = service.listRepos("octocat");

2 Retrofit注解

下面我们再介绍下Retrofit的注解,了解了Retrofit以后就知道各种网络请求场景如何使用了。

REQUEST METHOD

每个接口方法都需要定义一个请求类型和相对URL,Retrofit支持http请求的5种请求方式的注解: GET, POST, PUT, DELETE, 和HEAD

@GET("users/list")

也可以直接在URL里拼接get请求参数,但是不建议这么做会大大降低代码的灵活性。

@GET("users/list?sort=desc")
URL MANIPULATION

我们在接口请求的时候常用的参数传递方法有很多,Retrofit基本都支持,可以通过在URL中使用括号来定义Path参数,在方法中定义@Path注解表示该参数映射到URL括号中的字段。

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

也可以在方法参数中通过@Query注解来定义get请求的参数。

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

如果参数比较多,也可以定义@QueryMap组合成Map键值对来传递参数。

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
REQUEST BODY

对于请求中我们还经常使用post方式的请求,post请求和get请求最大的区别,我相信大家也都知道就是post请求会将请求报文放到requestBody中,所以这里我们定义该接口的请求方式为POST方式,参数通过@Body来指定请求报文,这里可以直接定义成可序列化对象,Retrofit会将报文中的请求JSON串自动转换为Bean,默认使用的JSON库是Gson,如果我们要调整为fastjson或者jackson都需要在buile Retrofit实例的时候设置convert工厂类,这里就不详细讲了,使用默认的就ok。

@POST("users/new")
Call<User> createUser(@Body User user);
HEADER MANIPULATION

如果接口有一些Http的header静态参数需要设置,这里我们就可以使用@Headers 注解,来定义Header中的参数,Header中的参数也都是定义成Map的形式。

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);

如果Header中存在动态参数,那么可以在方法的入参通过 @Header 注解来表示该参数是从请求的header中获取。

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)

3 Retrofit同步接口调用

所有的接口的返回值都是Call的实例,Call实例在执行接口请求的时候,不管是同步还是异步请求都只能使用一次,如果希望在页面中多次使用,那么可以通过Call实例的clone()方法创建一个新的实例用于请求接口。在java项目中可以直接使用Retrofit的同步调用,所以比较简单,对于Android请求,因为android系统要求主线程中不能使用同步网络请求,只能在自线程中使用异步网络请求。

使用同步接口调用非常简单,获取到接口接口的Call实例后直接调用execute,获取body就可以获取接口中定义的返回值:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GitHub github = retrofit.create(GitHub.class);

        Call<List<Contributor>> call = github.contributors("square", "retrofit");

        List<Contributor> contributors = call.execute().body();
        for (Contributor contributor : contributors) {
            System.out.println(contributor.login + " (" + contributor.contributions + ")");
        }

4 Retrofit异步接口调用

Retrofit也是支持异步接口调用的,异步接口调用和其他异步网络请求是一样的,都需要定义callback回调,下面我们先看下代码和同步的有什么区别。

Call<List<Contributor>> callAsync = github.contributors("spring-cloud","spring-cloud-netflix");
        callAsync.enqueue(new Callback<List<Contributor>>() {
            @Override
            public void onResponse(
                    Call<List<Contributor>> call, Response<List<Contributor>> response) {
                try {
                    System.out.println("====retrofit async=====");
                    for (Contributor contributor : response.body()) {
                        System.out.println(contributor.login + " (" + contributor.contributions + ")");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<List<Contributor>> call, Throwable t) {
                t.printStackTrace();
            }
        });

从代码中可以看到,在调用Call的enqueue方法的时候传了一个匿名Callback类,在匿名类中重写了onResponse()和onFailure()两个方法,我们来看下enqueue方法和Callback接口的源码,从源码中可以看到都定义了范型,可以支持用户自定义返回类型。

  /**
   * Asynchronously send the request and notify {@code callback} of its response or if an error
   * occurred talking to the server, creating the request, or processing the response.
   */
  void enqueue(Callback<T> callback);
public interface Callback<T> {
  /**
   * Invoked for a received HTTP response.
   * <p>
   * Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
   * Call {@link Response#isSuccessful()} to determine if the response indicates success.
   */
  void onResponse(Call<T> call, Response<T> response);

  /**
   * Invoked when a network exception occurred talking to the server or when an unexpected
   * exception occurred creating the request or processing the response.
   */
  void onFailure(Call<T> call, Throwable t);
}

5 Android接口访问使用Retrofit

在Android中使用Retrofit其实很简单,和上一节将的异步调用是一样的,我们只需要定义好Retrofit远程调用接口,在使用的时候定义Callback类就可以了,在Callback的onResponse回调方法中定义,请求成功后执行什么UI操作,在onFailure发法中定义请求失败后调用什么UI操作,这里就没什么好解释的了。

public void onCBtnClick(View view){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        SimpleService.GitHub github = retrofit.create(SimpleService.GitHub.class);

        Call<List<SimpleService.Contributor>> callAsync = github.contributors("spring-cloud","spring-cloud-netflix");
        callAsync.enqueue(new Callback<List<SimpleService.Contributor>>() {
            @Override
            public void onResponse(
                    Call<List<SimpleService.Contributor>> call, Response<List<SimpleService.Contributor>> response) {
                try {
                    System.out.println("====retrofit async=====");
                    for (SimpleService.Contributor contributor : response.body()) {
                        sb.append(contributor.login + " (" + contributor.contributions + ") \n");
                        System.out.println(contributor.login + " (" + contributor.contributions + ")");
                    }
                    textView.setText(sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<List<SimpleService.Contributor>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

6 Android RxJava+Retrofit

说到Retrofit就不得说到另一个库RxJava,网上已经不少文章讲如何与Retrofit结合,但这里还是会有一个RxJava的例子,不过这里主要目的是介绍使用CallAdapter所带来的效果。
CallAdapter则可以对Call转换,这样的话Call<T>中的Call也是可以被替换的,而返回值的类型就决定你后续的处理程序逻辑,同样Retrofit提供了多个CallAdapter,这里以RxJava的为例,用Observable代替Call:

引入RxJava支持:

    compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'

通过RxJavaCallAdapterFactory为Retrofit添加RxJava支持:

Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("https://api.github.com")
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 
      .build();

接口设计:

    public interface GitHub {
        @GET("/repos/{owner}/{repo}/contributors")
        Call<List<Contributor>> contributors(
                @Path("owner") String owner,
                @Path("repo") String repo);
    }

使用:

BlogService service = retrofit.create(BlogService.class);
GitHub github = retrofit.create(GitHub.class);
github.contributors("square", "retrofit");
  .subscribeOn(Schedulers.io())
  .subscribe(new Subscriber<List<Contributor>>() {
      @Override
      public void onCompleted() {
        System.out.println("onCompleted");
      }

      @Override
      public void onError(Throwable e) {
        System.err.println("onError");
      }

      @Override
      public void onNext(List<Contributor> contributors) {
        for (Contributor contributor : contributors) {
            System.out.println(contributor.login + " (" + contributor.contributions +            ")");
        }      
      }
  });

结果:

I/System.out: spencergibb (691)
I/System.out: dsyer (490)
I/System.out: ryanjbaxter (238)
I/System.out: marcingrzejszczak (52)
I/System.out: gzurowski (22)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容