Retrofit of Android open source framework

Retrofit is a type-safe HTTP client, available in both Android and Java. Retrofit implements a RESTful network interface through annotations, and the bottom layer uses Okhttp to complete the implementation of network requests. In addition, Retrofit encapsulates the switching of the main thread and sub-threads and the analysis of network data, which is much more convenient than OkHttp in use.

How to use Retrofit

  • Add dependency
dependencies {
    
    
    //Retrofit依赖
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    //Gson转换器,将网络响应使用Gson转换成Java Bean
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
}

Note: If ProGuard is used, it also needs to be configured in the proguard-rules.pro file:

#平台对Android上不存在的类型调用Class.forName来确定平台。
-dontnote retrofit2.Platform

#在iOS上的RoboVM上运行时使用的平台。将不会在运行时使用。
-dontnote retrofit2.Platform$IOS$MainThreadExecutor

#在Java 8虚拟机上运行时使用的平台。将不会在运行时使用。
-dontwarn retrofit2.Platform$Java8

#保留泛型类型信息,以供转换器和适配器的反射使用。
-keepattributes Signature

#保留声明的已检查异常以供代理实例使用。
-keepattributes Exceptions

-dontwarn okio.**
-dontwarn javax.annotation.**

# Gson
-keep class com.example.testing.retrofitdemo.bean.**{
    
    *;} # 自定义数据模型的bean目录
  • Defining the web service interface
    Create an interface that is specifically responsible for defining the web API. For example, we define the interface GitHubService to debug GitHub's open API, and one API corresponds to one method.
public interface GitHubService {
    
    
   //配置GET请求和URL路径
    @GET("users/{user}/repos")
    //返回为Call<T>对象,泛型T表示网络解析后结果的类型
    //@Path("user")注解表示参数user会替换URL路径中的{user}
    Call<List<Repo>> listRepos(@Path("user") String user);//返回值必须声明成Retrofit中内置的Call类型,并通过泛型来指定服务器响应的数据应该装换成什么对象。
}
  • Generate the corresponding Java Bean class
    The network result obtained by Github's network API is a JSON string, so we can generate the corresponding Java Bean class, as shown in the figure below.
    Insert picture description here
  • To implement the web service interface,
    we use the Builder mode to create a Retrofit object and configure the base address of the API:
 //在oncreate方法中创建Retrofit对象
 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())//配置Gson转换器
                .build();
  //使用Retrofit对象返回一个GitHubService的实现
  GitHubService gitHubService = retrofit.create(GitHubService.class);
  • Send network request
    Add network permissions in AndroidManifest.xml:
   <uses-permission android:name="android.permission.INTERNET"/>

Then use the githubService call interface method to obtain a Call object, and then use the object enqueue method to asynchronously send network requests:

//在oncreate方法中添加下述代码
Call<List<Repo>> octocat = gitHubService.listRepos("octocat");
        octocat.enqueue(mCallback);
//Retrofit会自动根据注解中配置的服务器接口地址去进行网络请求,服务器响应的数据会回调到enqueue方法中传入的Callback实现里面。需要注意的是,当发起请求的时候,retrofit会自动在内部开启子线程,当数据回调到Callback中之后会自动切换回主线程,整个操作过程不用考虑线程切换问题。
private Callback<List<Repo>> mCallback = new Callback<List<Repo>>() {
    
    
        @Override
        public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
    
    
            List<Repo> body = response.body();
            for (int i = 0; i < body.size(); i++) {
    
    
                Repo repo = body.get(i);
                Log.d(TAG, "onResponse: " + repo.getName());
            }
        }

        @Override
        public void onFailure(Call<List<Repo>> call, Throwable t) {
    
    
            Log.d(TAG, "onFailure: " + t.getLocalizedMessage());
        }
    };
  • operation result
    Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36828822/article/details/105993489