RequestBack.java
2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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());
}
}