有个需求:
需要对目前的网络请求框架进行二次封装,到达将来替换网络框架一改全改的效果
以封装xutils3的网络请求模块为例:
public interface WyCallBack {
void onSuccess(String result);
void onError(String error);
void onCancel(String cancel);
void onFinish(String finish);
}
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
public class WyHttp {
static WyCallBack mWyCallBack =null;
public static void setCallBack(WyCallBack wyCallBack) {
mWyCallBack = wyCallBack;
}
public static void getHttp(String url) {
RequestParams params = new RequestParams(url);
x.http().get(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
mWyCallBack.onSuccess(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
mWyCallBack.onError(ex.getMessage());
}
@Override
public void onCancelled(CancelledException cex) {
// Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
mWyCallBack.onCancel(cex.toString());
}
@Override
public void onFinished() {
mWyCallBack.onFinish("网络请求任务完全结束");
}
});
}
}
public class MainActivity extends AppCompatActivity implements WyCallBack {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCallBack(this);
// 进行get请求
WyHttp.getHttp("https://www.baidu.com/s");
}
@Override
public void onSuccess(final String result) {
WyLogUtils.e("onSuccess: "+result);
}
@Override
public void onError(final String error) {
WyLogUtils.e("onError: "+error);
}
@Override
public void onCancel(final String cancel) {
WyLogUtils.e("cancel: "+cancel);
}
@Override
public void onFinish(final String finish) {
WyLogUtils.e("finish: "+finish);
}
}
log工具类
public class WyLogUtils {
public static String customTagPre = "wy";
private static boolean isDebug = true;
public static void e(String deBugInfo) {
if (isDebug) {
StackTraceElement caller = Thread.currentThread().getStackTrace()[4];
String tag = generateTag(caller);
Log.e(tag, deBugInfo);
}
}
private static String generateTag(StackTraceElement caller) {
String tag = "%s.%s(L:%d)";
String callerClazzName = caller.getClassName();
callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber());
tag = TextUtils.isEmpty(customTagPre) ? tag : customTagPre + ":" + tag;
return tag;
}
}