Runt
2021-01-18 bf5729bbd51eeb83ebde68c1eaec98a26b9c0ee0
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package com.runt.sharedcode.utils;
 
import android.content.Context;
import android.util.Log;
 
import com.google.gson.Gson;
import com.runt.sharedcode.BaseApiResult;
 
import java.io.EOFException;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
 
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.Buffer;
import okio.BufferedSource;
 
/**
 * Created by EDZ on 2018/1/27.
 * 接口请求返回执行
 */
public abstract class MyStringCallBack<T extends BaseApiResult> extends PrintLogUtils  implements Callback {
    boolean  transHump;//是否转换驼峰命名
 
    public MyStringCallBack() {
        this.TAG = "MyStringCallBack";
    }
 
    @Override
    public void onFailure(Call call, final IOException e) {
        try {
            ArrayList<String> logList = getLogRequstList(call);
            String requestTime = call.request().header("requestTime");
            long tookMs =System.currentTimeMillis() - (requestTime == null ? 0 : Long.parseLong(requestTime));
            logList.add("<-- response url:"+URLDecoder.decode(call.request().url().toString(),"UTF-8")  );
            logList.add("<-- costtimes :  (" + tookMs + "ms"  + ')');
            logList.add("<-- "+e.getLocalizedMessage() );
            printLog(logList,false);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        if(e.getMessage().trim().equals("timeout")){
            doError(createError("网络超时"));
        }else{
            doError(createError("网络错误"));
        }
 
    }
 
    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        ArrayList<String> logList = getLogRequstList(call);
        logList.addAll(getLogResponseList(response));
        printLog(logList,true);
        final String jsonStr = new String(response.body().bytes());
 
        T param = null;
        try {
            Class<T> entityClass = (Class<T>) ((ParameterizedType) MyStringCallBack.this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            param =  new Gson().fromJson(transHump?GsonUtils.toHumpJson(jsonStr):jsonStr,entityClass);
        } catch (NumberFormatException e) {
            param = createError("数字类型转换错误"+e.getMessage());
        } catch (ClassCastException e) {
            e.printStackTrace();
            param = (T) new BaseApiResult<String>();
            param.msg = "实例化对象错误,未指定泛型实体类";
        }
 
        if(param == null   ){
            doError(null);
            return;
        }else if( param.code == 0 && param.msg == null && param.data == null){//如果返回值不存在
            param.code = 200;
        }
        if (  param.code == 200 ) {
            doSuccess (param);
        }else{
            doError(param);
        }
 
    }
 
    public T createError(String msg){
        try {
            Class<T> entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            T t = entityClass.newInstance();//实例化一个泛型
            t.msg = msg;//设置错误信息
            return  t;
        } catch (ClassCastException e) {
            e.printStackTrace();
            T t = (T) new BaseApiResult<String>();
            t.msg = "实例化对象未指定泛型实体类";
            return  t;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public abstract void doError(T error);
 
    public abstract void doSuccess(T result);
 
 
    final Charset UTF8 = Charset.forName("UTF-8");
 
    /**
     * 获取请求的log信息
     * @param call
     * @return
     * @throws IOException
     */
    private ArrayList<String> getLogRequstList(Call call) throws IOException {
        Request request = call.request();
        ArrayList<String> logArrays = new ArrayList<>();
        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;
        String requestStartMessage = "--> " + request.method() + ' ' + URLDecoder.decode(request.url().toString() ,"UTF-8")+ ' ' ;
        if ( hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logArrays.add(requestStartMessage);
        Headers headers = request.headers();
        logArrays.add("---------->REQUEST HEADER<----------");
        for (int i = 0, count = headers.size(); i < count; i++) {
            logArrays.add(headers.name(i) + ": " + headers.value(i));
        }
        if (!hasRequestBody) {
            logArrays.add("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logArrays.add("--> 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);
            }
            if (isPlaintext(buffer)) {
                logArrays.add("---------->REQUEST BODY<----------");
 
                logArrays.add(URLDecoder.decode(buffer.readString(charset), "UTF-8"));
                logArrays.add("--> END " + request.method()
                        + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logArrays.add("--> END " + request.method() + " (binary "
                        + requestBody.contentLength() + "-byte body omitted)");
            }
        }
        return logArrays;
 
    }
 
    /**
     *
     * 获取返回的log信息
     * @param response
     * @return
     * @throws IOException
     */
    private ArrayList<String> getLogResponseList( Response response) throws IOException {
        String requestTime = response.request().header("requestTime");
        long tookMs =System.currentTimeMillis() - (requestTime == null ? 0 : Long.parseLong(requestTime));
 
        ArrayList<String> logArrays = new ArrayList<>();
        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        logArrays.add("<-- response code:" + response.code() + " message:" + response.message()+" contentlength:"+bodySize  );
        logArrays.add("<-- response url:"+URLDecoder.decode(response.request().url().toString(),"UTF-8")  );
        logArrays.add("<-- costtimes :  (" + tookMs + "ms"  + ')');
 
 
        if ( !HttpHeaders.hasBody(response)) {
            logArrays.add("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logArrays.add("<-- 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 (!isPlaintext(buffer)) {
                logArrays.add("");
                logArrays.add("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return logArrays;
            }
 
            logArrays.add("---------->RESPONSE BODY<----------");
            if (contentLength != 0) {
                logArrays.add(GsonUtils.retractJson(buffer.clone().readString(charset)));
            }
 
            logArrays.add("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
        return logArrays;
    }
 
}