Commit 647e9f0b1adca7a740a08e4bbe8209d3a922735d

Authored by 朱显松
1 parent e6959934

add retrofit lib util

app/build.gradle
@@ -33,5 +33,6 @@ dependencies { @@ -33,5 +33,6 @@ dependencies {
33 compile 'com.android.support.constraint:constraint-layout:1.0.2' 33 compile 'com.android.support.constraint:constraint-layout:1.0.2'
34 // TODO 本地酷使用说明 代码仓库标识 34 // TODO 本地酷使用说明 代码仓库标识
35 // compile 'com.cnlive.libs:base:1.0.0@aar' 35 // compile 'com.cnlive.libs:base:1.0.0@aar'
36 - compile 'com.cnlive:cnlive:0.1.0' 36 + // compile 'com.cnlive:cnlive:0.1.0'
  37 + compile project(':cnlive')
37 } 38 }
cnlive/src/main/java/com/cnlive/libs/base/activity/MvpBindingActivity.java
@@ -5,7 +5,7 @@ import android.databinding.ViewDataBinding; @@ -5,7 +5,7 @@ import android.databinding.ViewDataBinding;
5 import android.os.Bundle; 5 import android.os.Bundle;
6 import android.support.annotation.NonNull; 6 import android.support.annotation.NonNull;
7 7
8 -import com.cnlive.libs.base.ReflectUtil; 8 +import com.cnlive.libs.base.util.ReflectUtil;
9 import com.hannesdorfmann.mosby.mvp.MvpActivity; 9 import com.hannesdorfmann.mosby.mvp.MvpActivity;
10 import com.hannesdorfmann.mosby.mvp.MvpPresenter; 10 import com.hannesdorfmann.mosby.mvp.MvpPresenter;
11 import com.hannesdorfmann.mosby.mvp.MvpView; 11 import com.hannesdorfmann.mosby.mvp.MvpView;
cnlive/src/main/java/com/cnlive/libs/base/fragment/MvpBindingFragment.java
@@ -9,7 +9,7 @@ import android.view.LayoutInflater; @@ -9,7 +9,7 @@ import android.view.LayoutInflater;
9 import android.view.View; 9 import android.view.View;
10 import android.view.ViewGroup; 10 import android.view.ViewGroup;
11 11
12 -import com.cnlive.libs.base.ReflectUtil; 12 +import com.cnlive.libs.base.util.ReflectUtil;
13 import com.hannesdorfmann.mosby.mvp.MvpFragment; 13 import com.hannesdorfmann.mosby.mvp.MvpFragment;
14 import com.hannesdorfmann.mosby.mvp.MvpPresenter; 14 import com.hannesdorfmann.mosby.mvp.MvpPresenter;
15 import com.hannesdorfmann.mosby.mvp.MvpView; 15 import com.hannesdorfmann.mosby.mvp.MvpView;
cnlive/src/main/java/com/cnlive/libs/base/model/IBaseInfo.java 0 → 100644
  1 +package com.cnlive.libs.base.model;
  2 +
  3 +
  4 +import java.io.Serializable;
  5 +
  6 +public interface IBaseInfo extends Serializable {
  7 + String getCode();
  8 +
  9 + String getMessage();
  10 +}
cnlive/src/main/java/com/cnlive/libs/base/network/ClientInterceptor.java 0 → 100644
  1 +package com.cnlive.libs.base.network;
  2 +
  3 +
  4 +import android.content.Context;
  5 +
  6 +import java.io.IOException;
  7 +
  8 +import okhttp3.Interceptor;
  9 +import okhttp3.Request;
  10 +import okhttp3.Response;
  11 +
  12 +class ClientInterceptor implements Interceptor {
  13 +
  14 + private Context mContext;
  15 +
  16 + ClientInterceptor(Context context) {
  17 + mContext = context;
  18 + }
  19 +
  20 + @Override
  21 + public Response intercept(Chain chain) throws IOException {
  22 + Request request = chain.request();
  23 +
  24 + Response response = chain.proceed(request);
  25 + if (NetworkUtil.isConnectInternet(mContext)) {
  26 + int maxAge = 60 * 60; // read from cache for 1 minute
  27 + response.newBuilder()
  28 + .addHeader("Cache-Control", "public, max-age=" + maxAge)
  29 + .build();
  30 +
  31 + } else {
  32 + int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
  33 + response.newBuilder()
  34 + .addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
  35 + .build();
  36 + }
  37 +
  38 + return response;
  39 + }
  40 +}
0 \ No newline at end of file 41 \ No newline at end of file
cnlive/src/main/java/com/cnlive/libs/base/network/NetworkUtil.java 0 → 100644
  1 +package com.cnlive.libs.base.network;
  2 +
  3 +import android.content.Context;
  4 +import android.net.ConnectivityManager;
  5 +import android.net.NetworkInfo;
  6 +
  7 +public class NetworkUtil {
  8 +
  9 + private static ConnectivityManager connectManager;
  10 +
  11 + private static void initConnectivityManager(Context context) {
  12 + if (connectManager == null) connectManager = (ConnectivityManager)
  13 + context.getSystemService(Context.CONNECTIVITY_SERVICE);
  14 + }
  15 +
  16 + public static boolean isConnectInternet(Context context) {
  17 + if (context == null) return false;
  18 + initConnectivityManager(context);
  19 +
  20 + if (connectManager != null) {
  21 + NetworkInfo networkinfo = connectManager.getActiveNetworkInfo();
  22 + return networkinfo != null && networkinfo.isAvailable();
  23 + }
  24 + return false;
  25 + }
  26 +
  27 +}
0 \ No newline at end of file 28 \ No newline at end of file
cnlive/src/main/java/com/cnlive/libs/base/network/RetrofitUtil.java 0 → 100644
  1 +package com.cnlive.libs.base.network;
  2 +
  3 +
  4 +import android.content.Context;
  5 +
  6 +
  7 +import com.cnlive.libs.base.util.LogUtil;
  8 +
  9 +import java.util.concurrent.TimeUnit;
  10 +
  11 +import javax.net.ssl.SSLContext;
  12 +import javax.net.ssl.SSLSocketFactory;
  13 +
  14 +import okhttp3.Cache;
  15 +import okhttp3.OkHttpClient;
  16 +import okhttp3.logging.HttpLoggingInterceptor;
  17 +import retrofit2.Retrofit;
  18 +import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
  19 +import retrofit2.converter.gson.GsonConverterFactory;
  20 +
  21 +public class RetrofitUtil {
  22 + private static boolean DEBUG = true;
  23 +
  24 + private static final String TAG = "RetrofitUtil";
  25 +
  26 + public static void setBuildType(boolean debug) {
  27 + DEBUG = debug;
  28 + }
  29 +
  30 + public static <T> T getRestAPI(String endpoint, Class<T> service) {
  31 +
  32 + return getRestAPI(null, false, true, 5000, 5000, endpoint, service);
  33 + }
  34 +
  35 + public static <T> T getRestAPI(String endpoint, Class<T> service, boolean showLog) {
  36 +
  37 + return getRestAPI(null, false, showLog, 5000, 5000, endpoint, service);
  38 + }
  39 +
  40 + private static <T> T getRestAPI(Context context, boolean hasCache, boolean showLog, int readTimeout, int connectTimeout, String endpoint, Class<T> service) {
  41 +
  42 + OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient().newBuilder();
  43 +
  44 + try {
  45 + SSLContext sslContext = SSLContext.getInstance("TLS");
  46 + sslContext.init(null, null, null);
  47 + SSLSocketFactory socketFactory = new Tls12SocketFactory(sslContext.getSocketFactory());
  48 + okHttpClientBuilder.sslSocketFactory(socketFactory);
  49 + } catch (Exception e) {
  50 + LogUtil.e(TAG, "RetrofitUtil", e);
  51 + }
  52 +
  53 + if (connectTimeout > 0) {
  54 + okHttpClientBuilder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
  55 + }
  56 + if (readTimeout > 0) {
  57 + okHttpClientBuilder.readTimeout(readTimeout, TimeUnit.SECONDS);
  58 + }
  59 + if (hasCache) {
  60 + okHttpClientBuilder.cache(new Cache(context.getCacheDir(), 10 * 1024 * 1024));
  61 + okHttpClientBuilder.addNetworkInterceptor(new ClientInterceptor(context));
  62 + }
  63 +
  64 + if (showLog) {
  65 + HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
  66 + httpLoggingInterceptor.setLevel(DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
  67 + okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
  68 + }
  69 +
  70 + Retrofit retrofit = new Retrofit.Builder()
  71 + .baseUrl(endpoint)
  72 + .client(okHttpClientBuilder.build())
  73 + .addConverterFactory(GsonConverterFactory.create())
  74 + .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
  75 + .build();
  76 +
  77 + return retrofit.create(service);
  78 + }
  79 +
  80 +
  81 +}
cnlive/src/main/java/com/cnlive/libs/base/network/Subscriber.java 0 → 100644
  1 +package com.cnlive.libs.base.network;
  2 +
  3 +import android.content.Context;
  4 +import android.content.Intent;
  5 +
  6 +
  7 +import com.cnlive.libs.base.model.IBaseInfo;
  8 +import com.cnlive.libs.base.util.LogUtil;
  9 +
  10 +import io.reactivex.annotations.NonNull;
  11 +import io.reactivex.disposables.Disposable;
  12 +import io.reactivex.functions.Action;
  13 +import io.reactivex.functions.Consumer;
  14 +import retrofit2.Response;
  15 +import retrofit2.adapter.rxjava2.Result;
  16 +
  17 +//TODO
  18 +//load_success_code - 加载成功
  19 +//load_failure_code - 加载失败
  20 +//load_error_code - 加载错误
  21 +//no_network_code - 没有网络
  22 +//
  23 +//特殊处理类型 (全局)
  24 +
  25 +public abstract class Subscriber<T extends IBaseInfo> {
  26 +
  27 + private static String success_code = "200";
  28 + private static final String unkonwn_error_code = "-1";
  29 + private static final String network_error_code = "-2";
  30 + private T mPageData;
  31 + private Context mContext;
  32 +
  33 +
  34 + public Subscriber(Context context) {
  35 + this.mContext = context;
  36 + }
  37 +
  38 + public Consumer<Result<T>> next = new Consumer<Result<T>>() {
  39 + @Override
  40 + public void accept(Result<T> data) throws Exception {
  41 + Response<T> response = data.response();
  42 + if (response != null) mPageData = response.body();
  43 + else if (!NetworkUtil.isConnectInternet(mContext)) onNetworkNoConnected();
  44 + else onError(unkonwn_error_code, network_load_fail);
  45 + }
  46 + };
  47 +
  48 + public Consumer<Throwable> error = new Consumer<Throwable>() {
  49 + @Override
  50 + public void accept(Throwable e) throws Exception {
  51 + LogUtil.d("NetLoader", "onError ", e);
  52 + if (mContext != null && !NetworkUtil.isConnectInternet(mContext))
  53 + onNetworkNoConnected();
  54 + else onError(unkonwn_error_code, e != null ? e.getMessage() : network_load_error);
  55 + }
  56 + };
  57 +
  58 + public Action complete = new Action() {
  59 + @Override
  60 + public void run() throws Exception {
  61 + if (mPageData != null && success_code.equals(mPageData.getCode())) {
  62 + onCompleted(mPageData);
  63 + } else if (mPageData != null) {
  64 + //TODO 特定请求类型
  65 + if (token_invalid.equals(mPageData.getCode())) {
  66 + onError(mPageData.getCode(), "用户信息已失效 ,请重新登录.");
  67 + onTokenInvalid();
  68 + } else {
  69 + onError(mPageData.getCode(), mPageData.getMessage());
  70 + }
  71 + } else {
  72 + if (mContext != null && !NetworkUtil.isConnectInternet(mContext))
  73 + onNetworkNoConnected();
  74 + else onError(unkonwn_error_code, network_load_fail);
  75 + }
  76 + }
  77 + };
  78 +
  79 + public Consumer<Disposable> subscribe = new Consumer<Disposable>() {
  80 + @Override
  81 + public void accept(@NonNull Disposable disposable) throws Exception {
  82 + onStart();
  83 + }
  84 + };
  85 +
  86 +
  87 + public abstract void onCompleted(T data);
  88 +
  89 + public abstract void onError(String code, String message);
  90 +
  91 + public void onNetworkNoConnected() {
  92 + onError(network_error_code, network_no_connected);
  93 + }
  94 +
  95 + public void onStart() {
  96 + }
  97 +
  98 +}
0 \ No newline at end of file 99 \ No newline at end of file
cnlive/src/main/java/com/cnlive/libs/base/network/Tls12SocketFactory.java 0 → 100644
  1 +package com.cnlive.libs.base.network;
  2 +
  3 +import java.io.IOException;
  4 +import java.net.InetAddress;
  5 +import java.net.Socket;
  6 +import java.net.UnknownHostException;
  7 +
  8 +import javax.net.ssl.SSLSocket;
  9 +import javax.net.ssl.SSLSocketFactory;
  10 +
  11 +public class Tls12SocketFactory extends SSLSocketFactory {
  12 + private static final String[] TLS_SUPPORT_VERSION = {"TLSv1.1", "TLSv1.2"};
  13 +
  14 + final SSLSocketFactory delegate;
  15 +
  16 + public Tls12SocketFactory(SSLSocketFactory base) {
  17 + this.delegate = base;
  18 + }
  19 +
  20 + @Override
  21 + public String[] getDefaultCipherSuites() {
  22 + return delegate.getDefaultCipherSuites();
  23 + }
  24 +
  25 + @Override
  26 + public String[] getSupportedCipherSuites() {
  27 + return delegate.getSupportedCipherSuites();
  28 + }
  29 +
  30 + @Override
  31 + public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
  32 + return patch(delegate.createSocket(s, host, port, autoClose));
  33 + }
  34 +
  35 + @Override
  36 + public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
  37 + return patch(delegate.createSocket(host, port));
  38 + }
  39 +
  40 + @Override
  41 + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
  42 + return patch(delegate.createSocket(host, port, localHost, localPort));
  43 + }
  44 +
  45 + @Override
  46 + public Socket createSocket(InetAddress host, int port) throws IOException {
  47 + return patch(delegate.createSocket(host, port));
  48 + }
  49 +
  50 + @Override
  51 + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
  52 + return patch(delegate.createSocket(address, port, localAddress, localPort));
  53 + }
  54 +
  55 + private Socket patch(Socket s) {
  56 + if (s instanceof SSLSocket) {
  57 + ((SSLSocket) s).setEnabledProtocols(TLS_SUPPORT_VERSION);
  58 + }
  59 + return s;
  60 + }
  61 +}
0 \ No newline at end of file 62 \ No newline at end of file
cnlive/src/main/java/com/cnlive/libs/base/network/TransformUtil.java 0 → 100644
  1 +package com.cnlive.libs.base.network;
  2 +
  3 +import com.google.gson.Gson;
  4 +
  5 +public class TransformUtil {
  6 +
  7 + public static <T> T transform(Class<T> clazz, Object object) {
  8 + Gson gson = new Gson();
  9 + String json = gson.toJson(object);
  10 + return gson.fromJson(json, clazz);
  11 + }
  12 +}
cnlive/src/main/java/com/cnlive/libs/base/ReflectUtil.java renamed to cnlive/src/main/java/com/cnlive/libs/base/util/ReflectUtil.java
1 -package com.cnlive.libs.base; 1 +package com.cnlive.libs.base.util;
2 2
3 3
4 -import com.cnlive.libs.base.util.LogUtil;  
5 -  
6 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Constructor;
7 import java.lang.reflect.Method; 5 import java.lang.reflect.Method;
8 import java.lang.reflect.ParameterizedType; 6 import java.lang.reflect.ParameterizedType;