在学习了鸿教主的两篇OKHttp的文章后,瞬间感觉OKHttp的高大上,在闲暇之余,将项目中的网络请求框架全部更换成OKHttp,当然在更换的过程中也有地方跟个人习惯有关,本人就在鸿教主的源码上做了一些适合自己的修改。
所以呢不知道鸿教主是谁的请绕道。。。
没有看过鸿教主的 Android 一个改善的okHttp封装库 请绕道。。。
网络请求:
这里我在onError方法中多加了个返回参数code状态码
private void request() {
Map<String, String> params = new HashMap<>();
params.put("currentPage", "1");
params.put("pageSize", "30");
OkHttpUtils
.get()
.url(Api.TALK_MAKEUP_LIST)
.params(params)
.tag(this)
.build()
.execute(new LoadingDialogCallback(this, Constants.NET_REQUEST_TXT) {
@Override
public void onResponse(String response) {
LogUtil.e(response);
}
@Override
public void onError(int code, Request request, Exception e) {
MyApplication.showResultToast(code, OkHttpTestActivity.this);
}
});
}
下面我们来看看showResultToast方法:
public static void showResultToast(int result, Context context) {
switch (result) {
case Constants.RESPONSE_EXCEPTION:
if (!NetUtils.isHasNet(context)) {
T.showShort(context, "当前网络不可用,请检查网络设置");
} else {
T.showShort(context, "响应异常,请重新发送请求");
}
break;
case Constants.RESPONSE_CANCLED:
T.showShort(context, "已取消请求");
break;
case Constants.RESPONSE_NOT_EXIST:
T.showShort(context, "对不起,您请求的地址不存在");
break;
default:
T.showShort(context, "请求响应失败,错误号" + result);
break;
}
}
这里我们做的更加人性化一点,没有网络时,给出Toast提示,用户按返回键取消网络请求时,给出取消请求Toast
在鸿洋封装的OkHttpUtils类中做相应修改,设置错误状态码:
package com.example.mytest.okhttp;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import android.os.Handler;
import android.os.Looper;
import com.example.mytest.okhttp.builder.GetBuilder;
import com.example.mytest.okhttp.builder.PostFileBuilder;
import com.example.mytest.okhttp.builder.PostFormBuilder;
import com.example.mytest.okhttp.builder.PostStringBuilder;
import com.example.mytest.okhttp.callback.Callback;
import com.example.mytest.okhttp.https.HttpsUtils;
import com.example.mytest.okhttp.request.RequestCall;
import com.example.mytest.utils.Constants;
import com.example.mytest.utils.LogUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
/**
* Created by zhy on 15/8/17.
*/
public class OkHttpUtils
{
public static final String TAG = "OkHttpUtils";
public static final long DEFAULT_MILLISECONDS = 10000;
private static OkHttpUtils mInstance;
private OkHttpClient mOkHttpClient;
private Handler mDelivery;
private OkHttpUtils()
{
mOkHttpClient = new OkHttpClient();
//cookie enabled
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
mDelivery = new Handler(Looper.getMainLooper());
if (true)
{
mOkHttpClient.setHostnameVerifier(new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
});
}
}
private boolean debug = Constants.DEBUG;
public static OkHttpUtils getInstance()
{
if (mInstance == null)
{
synchronized (OkHttpUtils.class)
{
if (mInstance == null)
{
mInstance = new OkHttpUtils();
}
}
}
return mInstance;
}
public Handler getDelivery()
{
return mDelivery;
}
public OkHttpClient getOkHttpClient()
{
return mOkHttpClient;
}
public static GetBuilder get()
{
return new GetBuilder();
}
public static PostStringBuilder postString()
{
return new PostStringBuilder();
}
public static PostFileBuilder postFile()
{
return new PostFileBuilder();
}
public static PostFormBuilder post()
{
return new PostFormBuilder();
}
public void execute(final RequestCall requestCall, Callback callback)
{
if (debug)
{
LogUtil.i("{method:" + requestCall.getRequest().method() + ", detail:" + requestCall.getOkHttpRequest().toString() + "}");
}
if (callback == null)
callback = Callback.CALLBACK_DEFAULT;
final Callback finalCallback = callback;
requestCall.getCall().enqueue(new com.squareup.okhttp.Callback()
{
@Override
public void onFailure(final Request request, final IOException e)
{
if(requestCall.getCall().isCanceled()){
sendFailResultCallback(Constants.RESPONSE_CANCLED, request, e, finalCallback);
}else{
sendFailResultCallback(Constants.RESPONSE_EXCEPTION, request, e, finalCallback);
}
}
@Override
public void onResponse(final Response response)
{
if (response.code() >= 400 && response.code() <= 599)
{
try
{
sendFailResultCallback(response.code(), requestCall.getRequest(), new RuntimeException(response.body().string()), finalCallback);
} catch (IOException e)
{
e.printStackTrace();
}
return;
}
try
{
Object o = finalCallback.parseNetworkResponse(response);
sendSuccessResultCallback(o, finalCallback);
} catch (IOException e)
{
sendFailResultCallback(response.code(), response.request(), e, finalCallback);
}
}
});
}
public void sendFailResultCallback(final int code, final Request request, final Exception e, final Callback callback)
{
if (callback == null) return;
mDelivery.post(new Runnable()
{
@Override
public void run()
{
callback.onError(code, request, e);
callback.onAfter();
}
});
}
public void sendSuccessResultCallback(final Object object, final Callback callback)
{
if (callback == null) return;
mDelivery.post(new Runnable()
{
@Override
public void run()
{
callback.onResponse(object);
callback.onAfter();
}
});
}
public void cancelTag(Object tag)
{
mOkHttpClient.cancel(tag);
}
public void setCertificates(InputStream... certificates)
{
HttpsUtils.setCertificates(getOkHttpClient(), certificates, null, null);
}
}
因为考虑到,加载进度对话框的复用性,修改起来的方便性,这里我们自己封装出一个带进度对话框的CallBack:
package com.example.mytest.okhttp.callback;
import java.io.IOException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.example.mytest.dialog.LoadingDialog;
import com.example.mytest.okhttp.OkHttpUtils;
import com.example.mytest.utils.Utils;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
/**
* Created by zhy on 15/12/14.
*/
public abstract class LoadingDialogCallback extends Callback<String>
{
private Context context;
private LoadingDialog dialog;
private String dialogStr;
public LoadingDialogCallback(Context context) {
super();
this.context = context;
}
public LoadingDialogCallback(Context context, String dialogStr) {
super();
this.context = context;
this.dialogStr = dialogStr;
}
@Override
public void onBefore(Request request) {
super.onBefore(request);
if (!Utils.isEmpty(dialogStr)) {
dialog = LoadingDialog.createDialog(context);
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
OkHttpUtils.getInstance().cancelTag(context);
}
});
dialog.setMessage(dialogStr);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
@Override
public void onAfter() {
super.onAfter();
if (dialog != null) {
dialog.dismiss();
}
}
@Override
public String parseNetworkResponse(Response response) throws IOException
{
return response.body().string();
}
}
OkHttpUtils.getInstance().cancelTag(context); 取消网络请求
好了,大功告成
最后感谢鸿教主无私地奉献,没有鸿教主的默默付出,哪有吾辈今天的幸福生活,鸿教主万岁万万岁!