Retrofit2框架使用总结

前言

Retrofit2是一个功能十分强大的网络加载框架,能够方便的向服务器请求数据并转换成对应的Java类,下面是我使用这个框架的一些总结:

1.添加依赖

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.google.code.gson:gson:2.7'
implementation'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'me.drakeet.multitype:multitype:3.4.4'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'

使用Retrofit2的话其实只需要添加第1,2,3,7个依赖就行了,第7个依赖是一个关于查看HTTP日志的框架,便于发现HTTP发送返回的数据是否正确。

2.写一个通过Retrofit2转换HTTP API为Java的接口,示例:

public interface API {
    @GET("users/{userid}/followers")
    Call<Response<List<User>>> getUsers(@Path("userid") String userid);
}

这里@GET中大括号内的内容要与@Path中的内容一致,可以动态的补全URL接口,并请求接口中的数据。

3.写一个工具类用以初始化一些必要操作并返回一个上一步创建的Java接口的一个对象

public class RetrofitHttpUtil {

    public static API getApi(){
        //Okhttp的拦截器用以记录HTTP请求和返回的数据
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();
        //创建一个Retrofit实例
        Retrofit retrofit=new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://stgapi.veervr.tv/")
                .client(client)
                .build();
        API api=retrofit.create(API.class);
        return api;
    }
}

4.向服务器发送请求并得到返回数据进行相应的处理

   API api = RetrofitHttpUtil.getApi();
   Call<Response<List<User>>> call = api.getUsers(selectText.getText().toString());
   call.enqueue(new Callback<Response<List<User>>>() {
       @Override
       public void onResponse(Call<Response<List<User>>> call, retrofit2.Response<Response<List<User>>> response) {
       	   //对返回数据进行处理
           userList.clear();
           Response<List<User>> userSingleResponse = response.body();
           userList.addAll(userSingleResponse.getData());
           //从查询到的粉丝用户数据中取出名字和头像信息
           initFollowerMessage();
           //添加item
           addItem();
           multiTypeAdapter.notifyDataSetChanged();
       }

       @Override
       public void onFailure(Call<Response<List<User>>> call, Throwable t) {
       //数据返回失败时的处理
           t.printStackTrace();
           Toast.makeText(MainActivity.this, "请求失败!", Toast.LENGTH_LONG).show();
       }
   });

注意:

  1. 数据返回失败时可能是因为写的Java类与返回的数据格式不对应或是网络连接出现问题造成的,应从日志中找出问题所在。
  2. 这里只是举了一个简单的@GET注解使用实例,其实@POST、@PUT等注解的用法大都相似,要注意的是与之相对应的注解的使用,如@POST对应@Field来指定参数
  3. 当然Retrofit2的使用远远不止于此,大家可以慢慢研究发现哈~

猜你喜欢

转载自blog.csdn.net/Chushiniudao/article/details/84781409