欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

35、RxJava\Okhttp\Retrofit 网络请求框架基本封装(一)

程序员文章站 2024-02-26 21:10:58
...

一、配置

    添加网络请求库 

  //    网络请求库
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'
    implementation 'com.google.code.gson:gson:2.7'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    //rxjava相关依赖
    implementation  'io.reactivex.rxjava2:rxjava:2.1.16'
    implementation  'io.reactivex.rxjava2:rxkotlin:2.2.0'
    implementation  'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    //日志拦截器
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

    注意:Rxjava 等代码存放在maven仓库中需要添加 mavenCentral() :

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

二、封装请求接口Service Retrofit

import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface RequestService {

//   https://free-api.heweather.com/s6/weather/forecast?location=beijing&key=5988e16bce934153b7692af4070391cc
    @GET("weather/forecast")
    Observable<ForecastBean> getForecast(@Query("location")String location, @Query("key")String key);

}

封装

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpGenerator {
    private static final String mBase_URL = "https://free-api.heweather.com/s6/";
    private static HttpGenerator mHttpGenerator;
    private Retrofit retrofit;

    public static HttpGenerator getInstance() {
        if (mHttpGenerator == null) {
            mHttpGenerator = new HttpGenerator();
        }
        return mHttpGenerator;
    }

    private HttpGenerator() {
        initOkhttp();
    }

    private void initOkhttp() {
        OkHttpClient client = HttpClientUtils.getHttpClient();
        retrofit = new Retrofit.Builder()
                .baseUrl(mBase_URL)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }


    public RequestService creatService() {
        return retrofit.create(RequestService.class);
    }

}


三、封装Okhttp

import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpClientUtils {

    public static OkHttpClient getHttpClient(){
        OkHttpClient client =  getUnsafeOkHttpClient();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = client.newBuilder()
                .retryOnConnectionFailure(true)
                .addInterceptor(interceptor)
                .connectTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();

        return client;
    }
    //兼容 对 Https 网络请求
    private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

四、调用

import android.util.Log;

import com.yixin.gweather.net.bean.ForecastBean;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class test {
    private RequestService service = HttpGenerator.getInstance().creatService();
    private ForecastBean mForecastBean ;
    public void testService(){
        Observable<ForecastBean> observable = service.getForecast("beijing","5988e16bce934153b7692af4070391cc");
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ForecastBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("onSubscribe","d");
                    }

                    @Override
                    public void onNext(ForecastBean forecastBean) {
                        //请求结果
                        mForecastBean = forecastBean;
                        Log.d("onNext","d");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("onError","d");
                    }

                    @Override
                    public void onComplete() {
                        Log.d("onComplete","d");
                    }
                });
    }
}

后记:

    本文知识网络请求的基本框架,后续还需要继续封装。

  1.     网络请求MPV封装
  2.     网络请求拦截器自定义
  3.     Rxjava返回结果、异常统一处理 
  4.     等   ... ... ss