Retrofit2+RxJava封装的网络框架(中)

2023-12-23 01:58

本文主要是介绍Retrofit2+RxJava封装的网络框架(中),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本篇主要把工具类的代码贴出,下篇讲解用法。

package com.abysskitty.frame.network;import rx.Subscriber;/*** Created by AbyssKitty on 2016/10/12.* Version 1.0* 可以在本类中对 Subscriber 获取到的数据进行处理。* 例如集中处理错误信息等*/
public class NetSubscriber<T> extends Subscriber<T> {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable e) {if("".equals(e.getLocalizedMessage().toString())){System.err.println("========================   C Net Error  ========================");System.err.println("custom DEBUG :Net Error = " + "数据解析错误,请检查解析type是否正确 (NetModle.******)");System.err.println("========================   E Net Error  ========================");}else{
//            Toast.makeText(BaseApplication.context,"错误的操作 或 服务器响应异常",Toast.LENGTH_SHORT).show();System.err.println("========================   C Net Error  ========================");System.err.println("custom DEBUG :Net Error = " + e.getLocalizedMessage());System.err.println("========================   E Net Error  ========================");}}@Overridepublic void onNext(T t) {}
}
package com.abysskitty.frame.network;import com.abysskitty.frame.network.bean.RespBean;/*** Created by AbyssKitty on 2016/10/18.* 使用接口 网络数据回调接口*/
public interface OnNetSubscriberListener {
//    void onNext(RespBean bean,Object data);void onNext(RespBean bean);void onError(Throwable e);
//    void onCompleted();
}
package com.abysskitty.frame.network.bean;import java.util.List;/*** Created by Administrator on 2016/10/19.*/
public class RespBean {public String message;    //返回信息public List list;       //list数据public Object obj;        //obj数据public String code;    //成功返回9999public String page;public String pageNum;public List depart; //部门public List user;public Object info;public String total;         //条数public String key;        //0public String returnCode; //返回码 正确=SUCCESSpublic RespDate resp;public String token;public String userId;
}

RespBean是数据回调初始化解析的Bean,需要根据具体的业务来自由定制(根据接口数据结构)。

下面是序列化log的代码

package com.abysskitty.frame.tool;import android.support.annotation.IntDef;
import android.support.annotation.Nullable;import com.abysskitty.frame.Switch;
import com.abysskitty.frame.network.loggingInterceptors.klog.BaseLog;
import com.abysskitty.frame.network.loggingInterceptors.klog.FileLog;
import com.abysskitty.frame.network.loggingInterceptors.klog.JsonLog;
import com.abysskitty.frame.network.loggingInterceptors.klog.XmlLog;import java.io.File;/*** This is a Log tool,with this you can the following* <ol>* <li>use KLog.d(),you could print whether the method execute,and the default tag is current class's* name</li>* <li>use KLog.d(msg),you could print log as before,and you could location the method with a click in* Android Studio Logcat</li>* <li>use KLog.json(),you could print json string with well format automatic</li>* </ol>** @author zhaokaiqiang*         github https://github.com/ZhaoKaiQiang/KLog*         15/11/17 扩展功能,添加对文件的支持*         15/11/18 扩展功能,增加对XML的支持,修复BUG*         15/12/8  扩展功能,添加对任意参数的支持*         15/12/11 扩展功能,增加对无限长字符串支持*         16/6/13  扩展功能,添加对自定义全局Tag的支持*/
public class LogUtil {/*** 是否显示Log,调试时打开,正式发布时关闭!!!* */private static boolean IS_SHOW_LOG = Switch.isDebug;public static final String LINE_SEPARATOR = System.getProperty("line.separator");public static final String NULL_TIPS = "Log with null object";private static final String DEFAULT_MESSAGE = "test here";private static final String PARAM = "Param";private static final String NULL = "null";private static final String TAG_DEFAULT = "mLogUtil";private static final String SUFFIX = ".java";public static final int JSON_INDENT = 4;public static final int V = 0x1;public static final int D = 0x2;public static final int I = 0x3;public static final int W = 0x4;public static final int E = 0x5;public static final int WTF = 0x6;public static final int JSON = 0x7;public static final int XML = 0x8;@IntDef({ V, D, I, W, E, WTF, JSON, XML })public @interface LogType {}private static final int STACK_TRACE_INDEX = 6;public static String mGlobalTag = TAG_DEFAULT;public static void init(boolean isShowLog) {IS_SHOW_LOG = isShowLog;}public static void init(boolean isShowLog, @Nullable String tag) {IS_SHOW_LOG = isShowLog;mGlobalTag = tag;}public static void v() {printLog(V, null, DEFAULT_MESSAGE);}public static void v(Object msg) {printLog(V, null, msg);}public static void v(String tag, Object... objects) {printLog(V, tag, objects);}public static void d() {printLog(D, null, DEFAULT_MESSAGE);}public static void d(Object msg) {printLog(D, null, msg);}public static void d(String tag, Object... objects) {printLog(D, tag, objects);}public static void i() {printLog(I, null, DEFAULT_MESSAGE);}public static void i(Object msg) {printLog(I, null, msg);}public static void i(String tag, Object... objects) {printLog(I, tag, objects);}public static void w() {printLog(W, null, DEFAULT_MESSAGE);}public static void w(Object msg) {printLog(W, null, msg);}public static void w(String tag, Object... objects) {printLog(W, tag, objects);}public static void e() {printLog(E, null, DEFAULT_MESSAGE);}public static void e(Object msg) {printLog(E, null, msg);}public static void e(String tag, Object... objects) {printLog(E, tag, objects);}public static void a() {printLog(WTF, null, DEFAULT_MESSAGE);}public static void a(Object msg) {printLog(WTF, null, msg);}public static void a(String tag, Object... objects) {printLog(WTF, tag, objects);}public static void json(String jsonFormat) {printLog(JSON, null, jsonFormat);}public static void json(String tag, String jsonFormat) {printLog(JSON, tag, jsonFormat);}public static void xml(String xml) {printLog(XML, null, xml);}public static void xml(String tag, String xml) {printLog(XML, tag, xml);}public static void file(File targetDirectory, Object msg) {printFile(null, targetDirectory, null, msg);}public static void file(String tag, File targetDirectory, Object msg) {printFile(tag, targetDirectory, null, msg);}public static void file(String tag, File targetDirectory, String fileName, Object msg) {printFile(tag, targetDirectory, fileName, msg);}public static void printLog(@LogType int type, String tagStr, Object... objects) {printLog(true, type, tagStr, objects);}public static void printLog(boolean showHeadString, @LogType int type, String tagStr,Object... objects) {if (!IS_SHOW_LOG) {return;}String[] contents = wrapperContent(tagStr, objects);String tag = contents[0];String msg = contents[1];String headString = contents[2];if (!showHeadString) {headString = "";}switch (type) {case V:case D:case I:case W:case E:case WTF:BaseLog.printDefault(type, tag, headString + msg);break;case JSON:JsonLog.printJson(tag, msg, headString);break;case XML:XmlLog.printXml(tag, msg, headString);break;}}private static void printFile(String tagStr, File targetDirectory, String fileName, Object objectMsg) {if (!IS_SHOW_LOG) {return;}String[] contents = wrapperContent(tagStr, objectMsg);String tag = contents[0];String msg = contents[1];String headString = contents[2];FileLog.printFile(tag, targetDirectory, fileName, headString, msg);}/*** @param tagStr TAG标签* @param objects 要打印的值*/private static String[] wrapperContent(String tagStr, Object... objects) {StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();StackTraceElement targetElement = stackTrace[STACK_TRACE_INDEX];String className = targetElement.getClassName();String[] classNameInfo = className.split("\\.");if (classNameInfo.length > 0) {className = classNameInfo[classNameInfo.length - 1] + SUFFIX;}if (className.contains("$")) {className = className.split("\\$")[0] + SUFFIX;}String methodName = targetElement.getMethodName();int lineNumber = targetElement.getLineNumber();if (lineNumber < 0) {lineNumber = 0;}String methodNameShort = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);String tag = (tagStr == null ? mGlobalTag : tagStr);String msg = (objects == null) ? NULL_TIPS : getObjectsString(objects);String headString = "[ (" + className + ":" + lineNumber + ")#" + methodNameShort + " ] ";return new String[] { tag, msg, headString };}private static String getObjectsString(Object... objects) {if (objects.length > 1) {StringBuilder stringBuilder = new StringBuilder();stringBuilder.append("\n");for (int i = 0; i < objects.length; i++) {Object object = objects[i];if (object == null) {stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(NULL).append("\n");} else {stringBuilder.append(PARAM).append("[").append(i).append("]").append(" = ").append(object.toString()).append("\n");}}return stringBuilder.toString();} else {Object object = objects[0];return object == null ? NULL : object.toString();}}
}

这篇关于Retrofit2+RxJava封装的网络框架(中)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/526330

相关文章

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

Java实现复杂查询优化的7个技巧小结

《Java实现复杂查询优化的7个技巧小结》在Java项目中,复杂查询是开发者面临的“硬骨头”,本文将通过7个实战技巧,结合代码示例和性能对比,手把手教你如何让复杂查询变得优雅,大家可以根据需求进行选择... 目录一、复杂查询的痛点:为何你的代码“又臭又长”1.1冗余变量与中间状态1.2重复查询与性能陷阱1.

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

Java利用@SneakyThrows注解提升异常处理效率详解

《Java利用@SneakyThrows注解提升异常处理效率详解》这篇文章将深度剖析@SneakyThrows的原理,用法,适用场景以及隐藏的陷阱,看看它如何让Java异常处理效率飙升50%,感兴趣的... 目录前言一、检查型异常的“诅咒”:为什么Java开发者讨厌它1.1 检查型异常的痛点1.2 为什么说

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

Java使用正则提取字符串中的内容的详细步骤

《Java使用正则提取字符串中的内容的详细步骤》:本文主要介绍Java中使用正则表达式提取字符串内容的方法,通过Pattern和Matcher类实现,涵盖编译正则、查找匹配、分组捕获、数字与邮箱提... 目录1. 基础流程2. 关键方法说明3. 常见场景示例场景1:提取所有数字场景2:提取邮箱地址4. 高级

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I