Retrofit的简单封装

1,178 阅读2分钟

0.目录等级

  • RequestData:网络返回的数据
  • Http:retrofit的网络实例化
  • RetrofitService:网络的接口注解显示
  • Server:网络接口的调用显示
  • SSLSocketFactoryUtils:https的处理

1.配置build.gradle

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
//okhttp3的日志打印
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
//retrofit的gson解析
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

2.新建网络返回数据RequestData

public class RequestData {
    private String msg;
    private int status;
    private ArrayList<Data> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public ArrayList<Data> getData() {
        return data;
    }

    public void setData(ArrayList<Data> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "msg = " + msg + "status = " + status;
    }
}

3.添加https的校验

public class SSLSocketFactoryUtils {
    /*
     * 默认信任所有的证书
     * */
    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{createTrustAllManager()}, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {

        }
        return sslSocketFactory;
    }

    public static X509TrustManager createTrustAllManager() {
        X509TrustManager tm = null;
        try {

            tm =   new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    //do nothing,接受任意客户端证书
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    //do nothing,接受任意服务端证书
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };
        } catch (Exception e) {

        }
        return tm;
    }
}

4.实例化Retrofit

public class Http {
    private static Http mInstance;

    //单利模式
    public static Http getInstance() {
        if (mInstance == null) {
            synchronized (Http.class) {
                if (mInstance == null) {
                    mInstance = new Http();
                }
            }
        }
        return mInstance;
    }

    public Retrofit getRetrofit(){
        HttpLoggingInterceptor loggingInterceptor;
        //打印网络请求相关日志
        loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.i("retrofitLog: ", message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //为了打印日志,需要配置OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                //配置SSlSocketFactory
                .sslSocketFactory(SSLSocketFactoryUtils.createSSLSocketFactory())
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.DOMAIN) // 设置 网络请求 Url
                .client(client)
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .build();

        return retrofit;
    }

    public RetrofitService getRetrofitService(){
        return getInstance().getRetrofit().create(RetrofitService.class);
    }
}

5.初始化RetrofitService接口注解

public interface RetrofitService {
    @GET("/api/user/modules")
    Call<RequestData> getModuleList(@Query("token") String token);

    @GET("/api/user/logout")
    Call<RequestData> logOutRequest(@Query("token") String token);
}

6.外部调用接口

public class Server {
    public static void getModuleList(String token,Callback<RequestData> callback){
        Http.getInstance().getRetrofitService().getModuleList(token).enqueue(callback);
    }

    public static void logOutRequest(String token,Callback<RequestData> callback){
        Http.getInstance().getRetrofitService().logOutRequest(token).enqueue(callback);
    }
}

目前接口使用同异步的网络请求.enqueue();

直接调用 Server.getModuleList()方法就可以

在使用过程中可以根据需求调整