Retrofit总结(原)

1、Retrofit的作用  

  A type-safe HTTP client for Android and Java

  看到这句话时候在想什么是类型安全?

  百度一下:类型安全代码指访问被授权可以访问的内存位置。例如,类型安全代码不能从其他对象的私有字段读取值。它只从定义完善的允许方式访问类型才能读取。类型安全的代码具备定义良好的数据类型

  所以看起来Retrofit定义类型安全的含义应该在于它的接口返回类型是用户定义好的,类型是安全的。

  Retrofit将网络请求封装起来,用户不需要怎么进行网络请求,只需要定义返回数据类型,给出url,框架就可以保证当用户请求时,返回的数据是你想要的数据。

  Retrofit依赖于OkHttp,可以对数据在返回时进行预处理等。

2、Retrofit的原理

3、Retrofit的实现

  Retrofit使用Builder模式来进行创建,可以自定义Call.Factory用于描述网络请求,

  

4、Retrofit的流程(看不清楚时建议下载或者图片另起网址打开)

5、Retrofit的使用

  5.1 Retrofit turns your HTTP API into a Java interface.  

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

  5.2 The Retrofit class generates an implementation of the GitHubService interface.

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

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

  5.3 Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver. 

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

     5.4 sync and async

  sync:  repos.execute(new Callback(){...});
  async:  repos.enqueue(new Callback(){...});

猜你喜欢

转载自www.cnblogs.com/weizhxa/p/9766157.html