Android Http库Retrofit随手笔记

介绍

Android上OkHttp在http请求上应用广泛,还可以使用OkHttp封装自己的网络请求接口。
假如很懒的话,可以直接上Retrofit2了,一个很成熟的网络请求库。
支持Okhttp3,Gson反序列化,Rxjava做线程管理,还有日志支持。

配置

build.gradle添加依赖:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
implementation 'com.squareup.okhttp3:logging-interceptor:3.14.9'

定义接口

public interface IdolService {
    @GET("idol/female/list")
    Observable<HttpResp<HttpRespPage<Idol>>> list(@Query("page") int page, @Query("pageSize") int pageSize);
}

初始化Retrofit

简单封装下,使用Gson反序列化成对象,并且使用Rxjava。

public class RetrofitApi {

    private static final String BASE_URL = "https://github.com/daweizhou89";

    private final Retrofit mRetrofit;
    public ConcurrentHashMap<Class, Object> mClassToService = new ConcurrentHashMap<>();

    private RetrofitApi() {
        final String baseUrl = BASE_URL;

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            // development build
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            // production build
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        }
        httpClient.addInterceptor(logging);

        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient.build())
                .build();
    }

    private static final class Holder {
        private static final RetrofitApi INSTANCE = new RetrofitApi();
    }

    public static RetrofitApi getInstance() {
        return RetrofitApi.Holder.INSTANCE;
    }

    public <T> T get(Class<T> clazz) {
        T service = (T) mClassToService.get(clazz);
        if (service == null) {
            service = mRetrofit.create(clazz);
            mClassToService.put(clazz, service);
        }
        return service;
    }
}

调用

HttpApi.getInstance().get(IdolService.class)
            .list(1, 10)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容