OkHttp和Retrofit简单上手

210 阅读2分钟

网络相关配置

首先在Config类配置好需要访问端点,资源地址,网络缓存目录大小等。

image.png

配置OkHttp

什么是OkHttp?

简单来说,OkHttp是Android中常用的库,用来收发http的。
同时还具有自动连接管理,缓存机制,拦截器等功能。

添加权限

AndroidManifest.xml中加入网络权限

<uses-permission android:name="android.permission.INTERNET" />

并且在<application... 中允许http请求

<application
android:usesCleartextTraffic="true"
...

添加依赖

在build.gradle(:app)加入以下依赖

//region
    
    //okhttp
    //https://github.com/square/okhttp
    implementation(libs.com.squareup.okhttp3.okhttp2)

    //打印okhttp请求日志
    implementation(libs.logging.interceptor)

    //retrofit
    //https://github.com/square/retrofit
    implementation(libs.retrofit)

    //使用gson解析json
    //https://github.com/google/gson
    implementation(libs.gson)

    //适配retrofit使用gson解析
    //版本要和retrofit一样
    implementation(libs.converter.gson)

    //适配retrofit支持rxjava
    implementation(libs.adapter.rxjava3)

    //使用了Android响应式编程
    //https://github.com/ReactiveX/RxAndroid
    implementation(libs.rxjava3.rxandroid)
    //endregion

封装OkHttp

创建一个网络依赖提供类,比如NetWorkModule,将OkHttp和Retrofit的实例创建方法封装进去。

public static OkHttpClient providerOkHttpClient() {
        //初始化okhttp
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

//         配置缓存
//         设置缓目录:AppContext的实例。在AppContext中有一个onCreate()方法,AppContext的实例
//         就是返回onCreate()方法的this指针。记得设置:android:name=".AppContext"。
        Cache cache = new Cache(AppContext.getInstance().getCacheDir(), Config.NETWORK_CACHE_SIZE);
        builder.cache(cache);

        builder.connectTimeout(10, TimeUnit.SECONDS) //设置连接超时时间
                .writeTimeout(10, TimeUnit.SECONDS)//设置发送超时时间
                .readTimeout(10, TimeUnit.SECONDS); //设置接收超时时间

        

        if (Config.DEBUG) {
            //调试模式

            //创建okhttp日志拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

            //设置日志等级
            loggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);

            //添加到网络框架中
            builder.addInterceptor(loggingInterceptor);

            //添加chucker实现应用内显示网络请求信息拦截器
            builder.addInterceptor(new ChuckerInterceptor.Builder(AppContext.getInstance()).build());
        }

        return builder.build();
    }

封装Retrofit

什么是Retrofit?

简单来说,Retrofit是一个与 RESTful API 交互的库,通过声明接口和注解自动生成HTTP请求,并将响应数据转换成 Java/Kotlin 对象,而OkHttp是Retrofit使用的底层HTTP客户端,负责实际的网络请求和连接管理。

封装Retrofit

public static Retrofit provideRetrofit(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()

                //让retrofit使用okhttp
                .client(okHttpClient)

                //api地址
                .baseUrl(Config.ENDPOINT)

                //适配rxjava
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())

                //使用gson解析json
                //将驼峰转下划线
                .addConverterFactory(GsonConverterFactory.create(JSONUtil.createGson()))

                //创建retrofit
                .build();
    }
}

测试Retrofit

private void testRetrofitGet() {
        OkHttpClient okHttpClient = NetworkModule.providerOkHttpClient();
        Retrofit retrofit = NetworkModule.provideRetrofit(okHttpClient);
        
        //创建service接口(request)
        DefaultService service = retrofit.create(DefaultService.class);
        
        service.yourRequest(some query parameter)
                //网络请求要在子线程运行
                .subscribeOn(Schedulers.io())
                
                /观察结果在主线程执行
                .observeOn(AndroidSchedulers.mainThread())
                
                //观察结果
                .subscribe(new Observer<yourResponse>() {
                   
                   
                   //剩下自动生成的代码
}