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;
|
}
|
|
}
|