RequestBack.java 2.68 KB
package com.polysoft.nafmii.net;

import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.polysoft.nafmii.enums.StateEnum;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Response;

public abstract class RequestBack<T> {

    void onParseResponse(Call call, Response response, Exception e) {
        if (null != e) {
            e.printStackTrace();
            this.onResponse(StateEnum.FAIL, null, e.getMessage());
            return;
        }
        int resCode = response.code();
        if (resCode < 200 && resCode >= 300) {
            String message = String.format("网络错误(%d)", resCode);
            this.onResponse(StateEnum.FAIL, null, message);
            return;
        }

        String string = null;
        try {
            string = response.body().string();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        if (TextUtils.isEmpty(string)) {
            String message = "返回数据格式错误";
            this.onResponse(StateEnum.FAIL, null, message);
            return;
        }

        JSONObject res = JSON.parseObject(string);
        String status = res.getString("status");
        if ("0".equals(status)) {
            String json = res.getString("data");
            Type type = this.getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                Type[] arguments = parameterizedType.getActualTypeArguments();
                if (this.isTypeCalss(arguments[0], String.class)) {
                    this.onResponse(StateEnum.OK, (T) json, null);
                } else if (this.isTypeCalss(arguments[0], JSONObject.class)) {
                    JSONObject data = res.getJSONObject("data");
                    this.onResponse(StateEnum.OK, (T) data, null);
                } else {
                    T data = JSON.parseObject(json, type);
                    this.onResponse(StateEnum.OK, data, null);
                }
            } else {
                this.onResponse(StateEnum.FAIL, null, "解析异常");
            }
        } else {
            String message = res.getString("statusText");
            this.onResponse(StateEnum.FAIL, null, message);
        }
    }

    protected abstract void onResponse(StateEnum state, T data, String message);

    private boolean isTypeCalss(Type type, Class c) {
        return c.toString().equals(type.toString());
    }
}