android Retrofit网络请求框架

转载自monkey01的博客[https://www.jianshu.com/p/8d857bf1f4f8]

1 Retrofit介绍

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

下面我们先简单说下使用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类型。

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> groupList(@Path(“id”) int groupId);

也可以在方法参数中通过@Query注解来定义get请求的参数。
@GET(“group/{id}/users”)
Call<List> groupList(@Path(“id”) int groupId, @Query(“sort”) String sort);

如果参数比较多,也可以定义@QueryMap组合成Map键值对来传递参数。
@GET(“group/{id}/users”)
Call<List> 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 createUser(@Body User user);

HEADER MANIPULATION
如果接口有一些Http的header静态参数需要设置,这里我们就可以使用@Headers 注解,来定义Header中的参数,Header中的参数也都是定义成Map的形式。
@Headers(“Cache-Control: max-age=640000”)
@GET(“widget/list”)
Call<List> widgetList();

@Headers({
“Accept: application/vnd.github.v3.full+json”,
“User-Agent: Retrofit-Sample-App”
})
@GET(“users/{username}”)
Call getUser(@Path(“username”) String username);

如果Header中存在动态参数,那么可以在方法的入参通过 @Header 注解来表示该参数是从请求的header中获取。
@GET(“user”)
Call 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中的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();

接口设计:
retrofit代理的接口的返回值变成了rxjava中的观察者

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

使用:
使用Schedulers.io()指定网络请求发生在io线程,而AndroidSchedulers.mainThread()指定获取到数据后的ui渲染发生android主线程

BlogService service = retrofit.create(BlogService.class);
GitHub github = retrofit.create(GitHub.class);
github.contributors("square", "retrofit");
  .subscribeOn(Schedulers.io())
  .observerOn(AndroidSchedulers.mainThread())
  .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 +            ")");
        }      
      }
  });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值