BaseObject
public class BaseObject implements Serializable, Cloneable {
private static final int ERROR_CODE_NO_DATA = 100;
private static final int ERROR_CODE_JSON_FORMAT = 101;
public int code = -1;
public String msg;
public void parse(String json) {
Log.d("parse", "parse: "+json);
if (TextUtils.isEmpty(json)) {
code = ERROR_CODE_NO_DATA;
return;
}
JSONObject obj;
try {
obj = new JSONObject(json);
} catch (Exception e) {
code = ERROR_CODE_JSON_FORMAT;
return;
}
code = obj.optInt("code");
Log.d("parse", "parse: code"+code);
msg = obj.optString("msg");
Log.d("parse", "parse: msg"+msg);
if (code==0||code==2007){
parse(obj);
}
}
/**
* 由子类实现自己的data部分解析
*
* @param dataObj
*/
public void parse(JSONObject dataObj) {
}
public BaseObject clone() {
BaseObject obj = null;
try {
obj = (BaseObject) super.clone();
} catch (CloneNotSupportedException var3) {
var3.printStackTrace();
}
return obj;
}
}
HttpCustomException
public class HttpCustomException extends Exception {
// 根据项目 自行添加 更改
public static final int EXCEPTION_JSON_ERROR = 3002;//请求Json数据格式错误
public static final int EXCEPTION_DEFAULT_HTTP = 102;//无网络连接
public static final int EXCEPTION_SEVER_HTTP = 5000;//服务器异常
public static final int EXCEPTION_TOKEN_INVALID = 1005;//Token失效
public static final int EXCEPTION_NOT_LOGIN = 1002;//未登录
public static final int EXCEPTION_FORMAT_INVALID = 406;//msg返回错误
public static final int EXCEPTION_WECHAT_NOT_PHONE = 2007;//微信未绑定手机
public static final int EXCEPTION_CODE_INVALID = 2006;//验证码错误
public static final int EXCEPTION_STOCK_NOT_ENOUGH = 2001;//库存不足
public final int code;
public final String msg;
public final IOException defaultExceptionp;
public HttpCustomException(int code, String msg, IOException defaultExceptionp) {
this.code = code;
this.msg = msg;
this.defaultExceptionp = defaultExceptionp;
}
@Override
public void printStackTrace() {
super.printStackTrace();
Log.d("sendFailed", "sendFailedStringCallback: "+"code = " + code + " msg = " + msg);
}
}
HttpManager
public class HttpManager {
private static HttpManager mInstance;
private final OkHttpClient mOkHttpClient;
private final Handler mDelivery;
private HttpManager() {
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
mDelivery = new Handler(Looper.getMainLooper());
}
public static HttpManager getInstance() {
if (mInstance == null) {
synchronized (HttpManager.class) {
if (mInstance == null) {
mInstance = new HttpManager();
}
}
}
return mInstance;
}
public void doGet(String url, final BaseObject baseObject, final ResultCallback callback) {
final Request request;
request = new Request.Builder()
.addHeader("App-System","Android")
.addHeader("charset", "utf-8")
.url(url)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess("GET-->" + request.url().toString(), response.body().string(), baseObject, callback);
}
});
}
public void doPost(String url, RequestBody requestBodyPost, final BaseObject baseObject, final ResultCallback callback) {
final Request requestPost = new Request.Builder()
.addHeader("App-System","Android")
.addHeader("charset", "utf-8")
.url(url)
.post(requestBodyPost).build();
mOkHttpClient.newCall(requestPost).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess("POST-->" + requestPost.url().toString() + "\n", response.body().string(), baseObject, callback);
}
});
}
public void doPatch(String url, RequestBody requestBodyPost, final BaseObject baseObject, final ResultCallback callback) {
final Request requestPatch = new Request.Builder()
.url(url)
.patch(requestBodyPost)
.build();
mOkHttpClient.newCall(requestPatch).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess("PATCH-->" + requestPatch.url().toString() + "\n", response.body().string(), baseObject, callback);
}
});
}
public void doPut(String url, RequestBody requestBodyPost, final BaseObject baseObject, final ResultCallback callback) {
final Request requestPut = new Request.Builder()
.url(url)
.put(requestBodyPost)
.build();
mOkHttpClient.newCall(requestPut).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess("PUT-->" + requestPut.url().toString() + "\n", response.body().string(), baseObject, callback);
}
});
}
public void doDelete(String url, final BaseObject baseObject, final ResultCallback callback) {
final Request requestDelete = new Request.Builder()
.url(url)
.delete()
.build();
mOkHttpClient.newCall(requestDelete).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess("DELETE-->" + requestDelete.url().toString() + "\n", response.body().string(), baseObject, callback);
}
});
}
public void doDelete(String url, RequestBody requestBody, final BaseObject baseObject, final ResultCallback callback) {
final Request requestDelete = new Request.Builder()
.url(url)
.delete(requestBody)
.build();
mOkHttpClient.newCall(requestDelete).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess("DELETE-->" + requestDelete.url().toString() + "\n", response.body().string(), baseObject, callback);
}
});
}
public void upLoad(String url, File file, RequestBody requestBodyPost, final BaseObject baseObject, final ResultCallback callback) {
final Request requestPost = new Request.Builder().url(url).post(requestBodyPost).build();
mOkHttpClient.newCall(requestPost).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_DEFAULT_HTTP, "", e), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
onResponseSuccess(requestPost.url().toString(), response.body().string(), baseObject, callback);
}
});
}
private void onResponseSuccess(String url, String body, BaseObject baseObject, ResultCallback callback) {
try {
LogUtil.print("http:url:+" + url + "\n<" + body + ">");
if (baseObject != null) {
baseObject.parse(body);
}
if (baseObject != null) {
if (baseObject.code == 0) {//0访问成功
sendSuccessResultCallback(baseObject, callback);
} else if (baseObject.code == EXCEPTION_STOCK_NOT_ENOUGH || baseObject.code == EXCEPTION_WECHAT_NOT_PHONE) {
//(访问成功)
sendSuccessResultCallback(baseObject, callback);
} else
sendFailedStringCallback(new HttpCustomException(baseObject.code, baseObject.msg, null), callback);
} else {
sendFailedStringCallback(new HttpCustomException(EXCEPTION_JSON_ERROR, "", null), callback);
}
} catch (Exception e) {
Log.d("onResponse", "onResponse: " + e.getMessage());
sendFailedStringCallback(new HttpCustomException(EXCEPTION_JSON_ERROR, "", null), callback);
}
}
/**
* 异步下载文件
*
* @param url
* @param destFile 本地文件存储的文件路径
* @param callback
*/
public void download(final String url, final File destFile, final ResultCallback callback) {
}
private void sendFailedStringCallback(final HttpCustomException e, final ResultCallback callback) {
if (callback == null) return;
if (callback.backgroundTask) {
// callback.onError(e); 增加了Toast通用处理,后台请求不发送error
callback.onFinish();
} else {
Log.d("2", "sendFailedStringCallback: " + e.code);
Log.d("2", "sendFailedStringCallback: " + e.msg);
mDelivery.post(new Runnable() {
@Override
public void run() {
if (e != null && e.defaultExceptionp != null && e.defaultExceptionp instanceof ConnectException) {
ToastUtil.showLongToast("连接超时,请重试");
} else {
if (!TextUtils.isEmpty(e.msg)) {
ToastUtil.showLongToast(e.msg + "-" + e.code);
} else {
ToastUtil.showLongToast("未知错误" + e.code);
}
}
callback.onError(e);
callback.onFinish();
}
});
}
}
//成功
private void sendSuccessResultCallback(final BaseObject object, final ResultCallback callback) {
if (callback == null) return;
if (callback.backgroundTask) {
callback.onResponse(object);
callback.onFinish();
} else {
mDelivery.post(new Runnable() {
@Override
public void run() {
callback.onResponse(object);
callback.onFinish();
}
});
}
}
private void sendDownloadStartCallback(final long total, final ResultCallback callback) {
if (callback == null) return;
if (callback.backgroundTask) {
callback.onDownloadStart(total);
} else {
mDelivery.post(new Runnable() {
@Override
public void run() {
callback.onDownloadStart(total);
}
});
}
}
private void sendProgressCallback(final long current, final long total, final ResultCallback callback) {
if (callback == null) return;
if (callback.backgroundTask) {
callback.onProgress(current, total);
} else {
mDelivery.post(new Runnable() {
@Override
public void run() {
callback.onProgress(current, total);
}
});
}
}
public static abstract class ResultCallback {
boolean backgroundTask = false;
public ResultCallback() {
this(false);
}
ResultCallback(boolean background) {
backgroundTask = background;
}
public void onError(HttpCustomException e) {
}
public abstract void onResponse(T data);
public abstract void onFinish();
void onDownloadStart(long total) {
}
void onProgress(long current, long total) {
}
}
}
HttpRequestV
public class HttpRequestV {
private static final String BASE_URL = "";
private static String url = "";
public static void get(BaseObject object,HttpManager.ResultCallback callback){
url=BASE_URL+"";
HttpManager.getInstance().doGet(url,object,callback);
}
public static void post(BaseObject object, HttpManager.ResultCallback callback){
RequestBody requestBody = new FormBody.Builder()
.build();
url=BASE_URL+"";
HttpManager.getInstance().doPost(url,requestBody,object,callback);
}
public static void delete( BaseObject object, HttpManager.ResultCallback callback){
url=BASE_URL+"";
RequestBody requestBody = new FormBody.Builder()
.build();
HttpManager.getInstance().doDelete(url,requestBody,object,callback);
}
public static void put(BaseObject object, HttpManager.ResultCallback callback){
RequestBody requestBody = new FormBody.Builder()
.build();
url = BASE_URL + "";
HttpManager.getInstance().doPut(url, requestBody, object, callback);
}
}