Retrofit的簡單封裝

納蘭寒明發表於2019-02-25

0.目錄等級

Retrofit的簡單封裝

  • 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()方法就可以

在使用過程中可以根據需求調整

相關文章