封装好的 rxjava+rxandroid + okhttp +rerofit2

public abstract class MyObserver<T> implements Observer<T> {
    public View mView;
    public ViewGroup pView;
    public TextView tv_msg;
    public LinearLayout ll_msg;
    public LoadingView pb;
    public Context mContext;
    boolean iserr = false;


    public abstract void onSuccess(T o);


    public abstract void onFail(Throwable e);


    public abstract void onRetry();




    public MyObserver(Context context, ViewGroup view) {


        pView = view;
        mContext = context;


        mView = pView.findViewById(R.id.net_main);


        if (mView == null) {
            mView = LayoutInflater.from(context).inflate(R.layout.common_net_progress, null);
            pView.addView(mView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        tv_msg = (TextView) mView.findViewById(R.id.tv_msg);
        ll_msg = (LinearLayout) mView.findViewById(R.id.ll_msg);
        pb = (LoadingView) mView.findViewById(R.id.pb);


        ll_msg.setVisibility(View.GONE);
        pb.setVisibility(View.VISIBLE);
        iserr = false;
        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iserr) {
                    onRetry();
                }
            }
        });




    }




    @Override
    public void onCompleted() {


    }


    @Override
    public void onError(Throwable e) {
        pb.setVisibility(View.GONE);
        ll_msg.setVisibility(View.VISIBLE);
        if (!NetworkUtils.isAvailable(mContext)) {
            tv_msg.setText("网络连接失败...");
        } else if (e instanceof UnknownHostException) {
            tv_msg.setText("请求失败...");
        } else {
            tv_msg.setText(e.getMessage());
        }
        onFail(e);
        e.printStackTrace();
        iserr = true;
    }


    @Override
    public void onNext(T o) {
        Base base = (Base) o;
        if (base.code != 0) {
            try {
                onError(new Exception(base.msg));
            }catch (Exception e){
                onError(e);
            }


        } else {
            LogUtils.e("TAG","成功 移除view");
            mView.setVisibility(View.GONE);
            pView.removeView(mView);
            onSuccess(o);
        }
    }


}



public class StoreApi {


    public static StoreApi instance;


    public StoreApiService service;


    private static Context context;


    public static class MyLog implements LoggingInterceptor.Logger {
        @Override
        public void log(String message) {
            LogUtils.i("oklog", "oklog: " + message);
        }
    }


    public StoreApi(Context context) {
        this.context = context;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.API_BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 添加Rx适配器
                .addConverterFactory(GsonConverterFactory.create()) // 添加Gson转换器
                .client(provideOkHttpClient(context))
                .build();
        service = retrofit.create(StoreApiService.class);
    }


    public static StoreApi getInstance(Context context) {
        if (instance == null)
            instance = new StoreApi(context);


        return instance;
    }




    
    public Observable<加实体类> 更换名称(Map<String, String> map) {
        Map<String, Object> maps = getDefMap();
        maps.putAll(map);
        return service.更换名称(sginParam(maps));
    }




    /**
     * 文件上传
     *
     * @param map
     * @return
     */
//    public Observable<UpLoadBean> upLoad(Map<String, String> map, List<File> files) {
//        Map<String, String> maps = getDefMap();
//        if (map != null) maps.putAll(map);
//        sginParam(maps);
//        int index = 0;
//        // new function
//        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//
//        for (String key : maps.keySet()) {
//            builder.addFormDataPart(key, maps.get(key));
//        }
//
//        for (File file : files) {
//            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"image" + index + "\";filename=\"" + file.getName() + "\""), RequestBody.create(MediaType.parse("image/*"), file)
//            );
//            index++;
//        }
//
//        MultipartBody body = builder.build();
//
//        return service.upLoad(body);
//    }
//
//
//


    /**
     * @return
     */


    public static Map<String, Object> getDefMap() {


        Map<String, Object> maps = new HashMap<>();
        maps.put("os_system", "android");
        maps.put("os_version", Build.VERSION.RELEASE);
        maps.put("app_version", Utils.getVersionName(context));
        maps.put("app_channel", Utils.getChannel(context, "UMENG_CHANNEL"));
        maps.put("app_name", Utils.getPackageName(context));
        maps.put("sys_imei", Utils.getIMEI(context));
        maps.put("sys_mac", "mac");
        maps.put("sys_idfa", "sys_idfa");
        maps.put("sys_screen", Utils.getWinWidth(context) + "x" + Utils.getWinHight(context));
        maps.put("net_type", Utils.getNetworkType(context));
        String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
        maps.put("timestamp", "" + System.currentTimeMillis() / 1000);
        maps.put("openId", MainApplication.open_id);
        maps.put("token", MainApplication.access_token);
        return maps;
    }


    public Map<String, Object> sginParam(Map<String, Object> map) {
        map.put("sign", SignUtil.signTopRequest(map));
        return map;
    }


    //
    public OkHttpClient provideOkHttpClient(Context context) {


        LoggingInterceptor logging = new LoggingInterceptor(new MyLog());
        logging.setLevel(LoggingInterceptor.Level.BODY);


        OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(true) // 失败重发
                .addInterceptor(new RequestInterceptor(context))
                .addInterceptor(logging);


        return builder.build();
    }




}

public interface StoreApiService {


    @FormUrlEncoded
    @POST("home/header.do")
    Observable<换成实体类> 自己更换名称(@FieldMap Map<String, Object> map);

}


package com.jlove.android.api.support;


import android.content.Context;


import com.jlove.android.utils.LogUtils;


import java.io.IOException;


import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Retrofit2 Cookie拦截器。用于保存和设置Cookies
 *
 */
public final class RequestInterceptor implements Interceptor {
    public Context context;
    public RequestInterceptor(Context context){
        this.context=context;
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
//        Request original = chain.request();
//        if (original.url().toString().contains("api/v1/")) {




            Request oldRequest=chain.request();
            HttpUrl.Builder builder=oldRequest.url().newBuilder().scheme(oldRequest.url().scheme()).host(oldRequest.url().host());
//                    .addQueryParameter("os_system","android")
//                    .addQueryParameter("os_version", Build.VERSION.RELEASE)
//                    .addQueryParameter("app_version", Utils.getVersionName(context))
//                    .addQueryParameter("app_channel",Utils.getChannel(context,"UMENG_CHANNEL"))
//                    .addQueryParameter("app_name",Utils.getPackageName(context))
//                    .addQueryParameter("sys_imei",Utils.getIMEI(context))
//                    .addQueryParameter("sys_mac","mac")
//                    .addQueryParameter("sys_idfa","sys_idfa")
//                    .addQueryParameter("sys_network",Utils.getNetworkType(context))
//                    .addQueryParameter("timestamp",String.valueOf(System.currentTimeMillis()))
//                    .addQueryParameter("sign","sign")
//                    .addQueryParameter("access_token","access_token");






            Request newRequest=oldRequest.newBuilder()
                    .method(oldRequest.method(),oldRequest.body())
                    .url(builder.build())
                    .build();
//        for (String key :newRequest.url().queryParameterNames() ) {
//            LogUtils.e("RequestInterceptor"," ..  "+key);
//        }
        LogUtils.e("RequestInterceptor",""+oldRequest.url().toString());
            return chain.proceed(newRequest);
//        }
//        return chain.proceed(original);
    }
}






/**
 * Retrofit2 Cookie拦截器。用于保存和设置Cookies
 *
 */
public final class RequestInterceptor implements Interceptor {
    public Context context;
    public RequestInterceptor(Context context){
        this.context=context;
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
//        Request original = chain.request();
//        if (original.url().toString().contains("api/v1/")) {




            Request oldRequest=chain.request();
            HttpUrl.Builder builder=oldRequest.url().newBuilder().scheme(oldRequest.url().scheme()).host(oldRequest.url().host());
//                    .addQueryParameter("os_system","android")
//                    .addQueryParameter("os_version", Build.VERSION.RELEASE)
//                    .addQueryParameter("app_version", Utils.getVersionName(context))
//                    .addQueryParameter("app_channel",Utils.getChannel(context,"UMENG_CHANNEL"))
//                    .addQueryParameter("app_name",Utils.getPackageName(context))
//                    .addQueryParameter("sys_imei",Utils.getIMEI(context))
//                    .addQueryParameter("sys_mac","mac")
//                    .addQueryParameter("sys_idfa","sys_idfa")
//                    .addQueryParameter("sys_network",Utils.getNetworkType(context))
//                    .addQueryParameter("timestamp",String.valueOf(System.currentTimeMillis()))
//                    .addQueryParameter("sign","sign")
//                    .addQueryParameter("access_token","access_token");






            Request newRequest=oldRequest.newBuilder()
                    .method(oldRequest.method(),oldRequest.body())
                    .url(builder.build())
                    .build();
//        for (String key :newRequest.url().queryParameterNames() ) {
//            LogUtils.e("RequestInterceptor"," ..  "+key);
//        }
        LogUtils.e("RequestInterceptor",""+oldRequest.url().toString());
            return chain.proceed(newRequest);
//        }
//        return chain.proceed(original);
    }
}





/**
 * Retrofit2 Logger拦截器。
 *
 */
public final class LoggingInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");


    public enum Level {
        /**
         * No logs.
         */
        NONE,
        /**
         * Logs request and response lines.
         * <p/>
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting HTTP/1.1 (3-byte body)
         * <p/>
         * <-- HTTP/1.1 200 OK (22ms, 6-byte body)
         * }</pre>
         */
        BASIC,
        /**
         * Logs request and response lines and their respective headers.
         * <p/>
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting HTTP/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         * --> END POST
         * <p/>
         * <-- HTTP/1.1 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         * <-- END HTTP
         * }</pre>
         */
        HEADERS,
        /**
         * Logs request and response lines and their respective headers and bodies (if present).
         * <p/>
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting HTTP/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         * <p/>
         * Hi?
         * --> END GET
         * <p/>
         * <-- HTTP/1.1 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         * <p/>
         * Hello!
         * <-- END HTTP
         * }</pre>
         */
        BODY
    }


    public interface Logger {
        void log(String message);


        /**
         * A {@link Logger} defaults output appropriate for the current platform.
         */
        Logger DEFAULT = new Logger() {
            @Override
            public void log(String message) {
                //Platform.get().log(4, message, null);
            }
        };
    }


    public LoggingInterceptor() {
        this(Logger.DEFAULT);
    }


    public LoggingInterceptor(Logger logger) {
        this.logger = logger;
    }


    private final Logger logger;


    private volatile Level level = Level.NONE;


    /**
     * Change the level at which this interceptor logs.
     */
    public LoggingInterceptor setLevel(Level level) {
        if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
        this.level = level;
        return this;
    }


    public Level getLevel() {
        return level;
    }


    @Override
    public Response intercept(Chain chain) throws IOException {
        Level level = this.level;


        Request request = chain.request();
        if (level == Level.NONE) {
            return chain.proceed(request);
        }


        boolean logBody = level == Level.BODY;
        boolean logHeaders = logBody || level == Level.HEADERS;


        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;


        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        String requestStartMessage =
                "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logger.log(requestStartMessage);


        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a network interceptor. Force
                // them to be included (when available) so there values are known.
                if (requestBody.contentType() != null) {
                    logger.log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    logger.log("Content-Length: " + requestBody.contentLength());
                }
            }


            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                // Skip headers from the request body as they are explicitly logged above.
                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                    logger.log(name + ": " + headers.value(i));
                }
            }


            if (!logBody || !hasRequestBody) {
                logger.log("--> END " + request.method());
            } else if (bodyEncoded(request.headers())) {
                logger.log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);


                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }


                logger.log("");
                logger.log(buffer.readString(charset));


                logger.log(
                        "--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            }
        }


        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);


        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        logger.log("<-- "
                + response.code()
                + ' '
                + response.message()
                + ' '
                + response.request().url()
                + " ("
                + tookMs
                + "ms"
                + (!logHeaders ? ", " + bodySize + " body" : "")
                + ')');


        if (logHeaders) {
            Headers headers = response.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                logger.log(headers.name(i) + ": " + headers.value(i));
            }


            if (!logBody || !HttpEngine.hasBody(response)) {
                logger.log("<-- END HTTP");
            } else if (bodyEncoded(response.headers())) {
                logger.log("<-- END HTTP (encoded body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();


                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }


                if (contentLength != 0) {
                    logger.log("");
                    logger.log(buffer.clone().readString(charset));
                }


                logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
            }
        }


        return response;
    }


    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }


    private static String protocol(Protocol protocol) {
        return protocol == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1";
    }

}







猜你喜欢

转载自blog.csdn.net/qq_32034593/article/details/80830586