Android 网络数据解析架构设计 拦截器里面修改服务器返回的数据

1.加密数据 格式 

{"head":{"rtnMsg":"本次请求成功!","rtnCode":"000000"},
"totalRecords":1,
"body":"r6ByxJarAIJ+3M6u3hEyiMt4MZPAG6D93y2ea8YaorYuGjxJMSxrjAJit969yiY/Sc/imtIu8NgAiKkCT21tBJ5JqL3fe+6B51nbZ9mWwoUTFsQLfqt7j4oP/mQ5cS8agPJfpXC0EMWL1r30aYayLL0qx1h/z41g0nOZ8qUwloII0M3tAwaxkTlzULlFIwDW"}

解密后的数据 

 {"body":"#[{\"createTime\":1515637774000,\"name\":\"demoName\",\"updateTime\":1515637785000,\"id\":\"D237A8CFF7124CA7BAB7EF1239E7E83B\",\"message\":\"demoMessage\"}]#",
"head":{"rtnCode":"000000","rtnMsg":"本次请求成功!"},
"totalRecords":1}

解密处理后的数据 

{"body":[{"createTime":1515637774000,"name":"demoName","updateTime":1515637785000,"id":"D237A8CFF7124CA7BAB7EF1239E7E83B","message":"demoMessage"}],
"head":{"rtnCode":"000000","rtnMsg":"本次请求成功!"},
"totalRecords":1}

通过retrofit 网络拦截器统一进行 网络请求返回数据的处理 ,业务代码不关心解密逻辑 

拦截器代码 


public class OkHttpLoggingInterceptor implements Interceptor {

    private String token;
    private boolean mIsdebug;

    public OkHttpLoggingInterceptor(boolean isdebug, String token) {
        this.mIsdebug = isdebug;
        this.token = token;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request.Builder newBuilder = chain
                .request()
                .newBuilder();

        Request request = newBuilder
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("Authorization", "Bearer " + token)
                .build();

        String cacheControl = request.cacheControl().toString();
//        if(TextUtils.isEmpty(cacheControl)){
//            cacheControl = "public, max-age=60";
//        }
        Response response = chain.proceed(request);

        if (mIsdebug) {
            log("response返回参数" + response.toString());

            //添加打印服务器返回的数据
            ResponseBody responseBody = response.body();
            long contentLength = responseBody.contentLength();
            BufferedSource source = responseBody.source();
            source.request(Integer.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();


            String backSource = buffer.clone().readString(Charset.forName("UTF-8"));
            if (contentLength != 0) {
                log("服务器返回原始加密数据:" + "" + backSource);
                JSONObject headJson = null;
                JSONObject all = null;
                try {
                    all = new JSONObject(backSource);
                    headJson = all.getJSONObject("head");

                    if (headJson.optString("rtnCode").equals("000000")) {

                        BaseBeanXD baseBeanXD = new Gson().fromJson(backSource, BaseBeanXD.class);

                        baseBeanXD.setBody("#"+EncryptUtils.getBase64Decode(baseBeanXD.getBody())+"#");

//                log("服务器解密后的:--- 2   " + baseBeanXD.getRequestBody());
                        String content = new Gson().toJson(baseBeanXD);
                        log("服务器解密后的:---    " + content);
                        String replace = content.replace("\"#", "").replace("#\"", "").replace("\\", "");
                        log("处理后的服务器数据=   " + replace);
                        Response build = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), replace)).build();
                        return build;

                    }else{
                        all.remove("body");
                        log(all.toString());
                        Response build = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), all.toString().replace("\\", ""))).build();

                        return build;

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        return response.
                newBuilder()
//                .header("Cache-Control", cacheControl)
                .build();

    }


    void log(String str) {
        if (mIsdebug) {
            LogUtil.e(str);
        }
    }

}

 

其中加密数据,是按string传进去的,解密之后 ,body后边会带 “{}” 或者“【】” ,通过添加一个特殊字符# ,把“” 去掉。

 

2.返回数据的适配 解析 

抽取基类 ResultBaseBeanXD   把head 字段抽取出来 。具体的返回bean 集成这个 类,来解析body 数据

public class ResultBaseBeanXD {

    protected HeadBean head;

    public HeadBean getHead() {
        return head;
    }

    public void setHead(HeadBean head) {
        this.head = head;
    }


    public static class HeadBean {
        /**
         * rtnMsg : 本次请求成功!
         * rtnCode : 000000
         */

        private String rtnMsg;
        private String rtnCode;

        public String getRtnMsg() {
            return rtnMsg;
        }

        public void setRtnMsg(String rtnMsg) {
            this.rtnMsg = rtnMsg;
        }

        public String getRtnCode() {
            return rtnCode;
        }

        public void setRtnCode(String rtnCode) {
            this.rtnCode = rtnCode;
        }
    }

}

 

3.回调数据的公共解析处理 

原始网络的callBack 如下 

public abstract class ACallback {
    public abstract void onSuccessA(T data);
    public abstract void onFailA(String errCode, String errMsg);
}

根据返回数据的  创建一个适配自己项目的callback . T可以 强转成我们的 基类ResultBaseBeanXD ,进行head 的判断处理

public abstract class NetCallBack extends ACallback {


    @Override
    public void onSuccessA(T data) {
        ResultBaseBeanXD bean  = (ResultBaseBeanXD) data;
        //当返回的请求code 不是这个 000000 的时候,不进行body 处理走onfail方法
        if(bean.getHead().getRtnCode().equals("000000")){
            onSuccess(data);
        }else{
            onFail(bean.getHead().getRtnCode(),bean.getHead().getRtnMsg());
        }
    }

    protected abstract void onSuccess(T data);

    @Override
    public void onFailA(String errCode, String errMsg) {
        onFail(errCode,errCode);
    }

    protected abstract void onFail(String errCode, String errCode1);
}

 

4.具体的类的写法 

/**
 * @description: 已支付订单
 * @author: Created by lsw
 * @date: 2018/9/18 16:10
 */
public class PayedResultBean extends ResultBaseBeanXD {


    /**
     * head : {"rtnMsg":"本次请求成功!","rtnCode":"000000"}
     * body : [{"createTime":1537176864000,"id":1,"mobile":"13021441372","name":"张三"}]
     */


    private List body;

    private long totalRecords;

    public long getTotalRecords() {
        return totalRecords;
    }

    public void setTotalRecords(long totalRecords) {
        this.totalRecords = totalRecords;
    }


    public List getBody() {
        return body;
    }

    public void setBody(List body) {
        this.body = body;
    }


    public static class BodyBean {
        /**
         * createTime : 1537176864000
         * id : 1
         * mobile : 13021441372
         * name : 张三
         */

        private long createTime;
        private long id;
        private String mobile;
        private String name;

        public long getCreateTime() {
            return createTime;
        }

        public void setCreateTime(long createTime) {
            this.createTime = createTime;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}


总之,根据项目的server 返回数据的具体 情况 ,自己来修改适配 网络请求。

你可能感兴趣的:(Interceptor,android,okhttp)