Retrofit2 一篇入门文章

280 阅读1分钟

Retrofit2 一篇入门文章

文章非原创,是对他人文章的实践、参考和整理。

Retrofit2可以理解为OkHttp更进一步的封装。

一、准备工作

引入retrofit的库,和gson解析的库

implementation 'com.squareup.retrofit2:retrofit:2.5.0'//Retrofit依赖
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'//可选依赖,解析json字符所用

找到一个可以使用的API接口,比如完整的能返回json的接口

https://m.kugou.com/plist/index&json=true&page=1

二、初步使用

1. 添加注解接口

public interface PlayListService {

    /*单个参数*/
    @GET("index/{page}")
    Call<ResponseBody> getPlayList(@Path("page") int id);

    /*多个参数*/
    @GET("index")
    Call<ResponseBody> getPlayList(@QueryMap Map<String, String> options);

}

2. 使用

public class MainActivity extends Activity {

    final String TAG = "MainActivity";
    Retrofit retrofit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        retrofit = new Retrofit.Builder()
                .baseUrl("https://m.kugou.com/plist/")
                .build();
    }

    public void TEST(View view) {
        PlayListService service = retrofit.create
                (PlayListService.class);
        Map<String, String> options = new HashMap<>();
        options.put("json", "true");
        options.put("page", "1");
        Call<ResponseBody> call = service.getPlayList(options);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String jsonStr = response.body().string();
                    Gson gson = new Gson();
                    PlayListInfo playListInfo = gson.fromJson(jsonStr, PlayListInfo.class);
                    Log.d(TAG, "访问成功:" + playListInfo.getSrc());
                    Log.d(TAG, "是否是主线程:" + (Looper.myLooper() == Looper.getMainLooper()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "call:" + t.toString());
            }
        });
    }
}

二、封装使用

当然实际项目中要封装的跟进一步。

1. 添加注解接口

注意泛型中的ResponseBody改成了实际对象

public interface PlayListService {
    /*多个参数*/
    @GET("index")
    Call<PlayListInfo> getPlayList(@QueryMap Map<String, String> options);
}

2. 对象

public class PlayListInfo {

    private String kg_domain;
    private String src;
    
    // getset 省略
}

3. 工具类

class GenServiceUtil {

    static final String BASE_URL = "https://m.kugou.com/plist/";

    private static final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static final Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create());

    private static final Retrofit retrofit = builder.client(httpClient.build()).build();

    public static <S> S createService(Class<S> serviceClass) {
        return retrofit.create(serviceClass);
    }

}

4. 使用

public class MainActivity extends Activity {

    final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void TEST(View view) {
        PlayListService service = GenServiceUtil.createService(PlayListService.class);
        Map<String, String> options = new HashMap<>();
        options.put("json", "true");
        options.put("page", "1");
        Call<PlayListInfo> call = service.getPlayList(options);
        call.enqueue(new Callback<PlayListInfo>() {
            @Override
            public void onResponse(Call<PlayListInfo> call, Response<PlayListInfo> response) {
                PlayListInfo playListInfo = response.body();
                if (playListInfo != null)
                    Log.d(TAG, "访问成功:" + playListInfo.getSrc());
                Log.d(TAG, "是否是主线程:" + (Looper.myLooper() == Looper.getMainLooper()));
            }

            @Override
            public void onFailure(Call<PlayListInfo> call, Throwable t) {

            }
        });
    }
}