XUtils3.0网络框架的使用以及在项目中的二次封装

2017-03-09  本文已影响1356人  我有一口小白牙

上步骤:
1, 添加依赖


添加依赖.png

2,在application中初始化XUtils, 记得在清单文件中写哦

初始化XUtils

3, 这个.....NetRequestUtils代码有点多:
import android.util.Log;

import com.diandou.bigdemo.utils.MLogUtil;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.Map;

public class NetRequestUtil {

public final Gson gson = new Gson();
private volatile static NetRequestUtil instance;

/**
 * Double Check 单例模式
 *
 * @return
 */
public static NetRequestUtil getInstance() {
    if (instance == null) {
        synchronized (NetRequestUtil.class) {
            if (instance == null) {
                instance = new NetRequestUtil();
            }
        }
    }
    return instance;
}

/**
 * 网络请求的接口回调监听器
 */
public interface NetResponseListener {
    void onSuccess(MResponse response, int requestCode);

    void onFailed(int requestCode);
}

/**
 * 文件下载的接口回调监听器
 */
public interface NetDownLoadFileListener extends NetResponseListener {

    void onSuccess(File response, int requestCode);

    void onLoading(long current, boolean isDownloading, int requestCode);
}

/**
 * 文件上传的接口回调监听
 */
public interface NetUpLoadFileListener extends NetResponseListener {
    void onLoading(long current, boolean isDownloading, int requestCode);
}




/**
 * 异步get请求
 *
 * @param url
 * @param maps
 * @param requestCode
 * @param clazz
 * @param listener
 * @return
 */
public Callback.Cancelable get(String url, Map<String, String> maps, final int requestCode, final Class<? extends MResponse> clazz, final NetResponseListener listener) {
    RequestParams params = new RequestParams(url);
    if (maps != null && !maps.isEmpty()) {
        for (Map.Entry<String, String> entry : maps.entrySet()) {
            params.addQueryStringParameter(entry.getKey(), entry.getValue());
        }
    }

    Callback.Cancelable cancelable = x.http().get(params, new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            MResponse mResponse = gson.fromJson(result, clazz);//按正常响应解析
            listener.onSuccess(mResponse, requestCode);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            listener.onFailed(requestCode);
        }

        @Override
        public void onCancelled(CancelledException cex) {
        }

        @Override
        public void onFinished() {

        }
    });
    return cancelable;
}

/**
 * 带缓存的异步get请求
 *
 * @param url
 * @param maps
 * @param requestCode
 * @param clazz
 * @param listener
 * @return
 */
public Callback.Cancelable getCache(String url, Map<String, String> maps, final int requestCode, final Class<? extends MResponse> clazz, final NetResponseListener listener) {
    RequestParams params = new RequestParams(url);
    if (maps != null && !maps.isEmpty()) {
        for (Map.Entry<String, String> entry : maps.entrySet()) {
            params.addQueryStringParameter(entry.getKey(), entry.getValue());
        }
    }

    // 默认缓存存活时间, 单位:毫秒(如果服务器没有返回有效的max-age或Expires则参考)
    params.setCacheMaxAge(1000 * 60);//设置缓存当这个缓存事件过了的时候, 这时候就会不走这个onCache方法, 直接发起网络请求,
    Callback.Cancelable cancelable = x.http().get(params, new Callback.CacheCallback<String>() {
        @Override
        public boolean onCache(String result) {
            MResponse mResponse = gson.fromJson(result, clazz);//按正常响应解析
            listener.onSuccess(mResponse, requestCode);
            return true;//这里返回一个true, 就是走了cache就不再发起网络请求了, 返回一个false, 就是不信任缓存数据, 再次发起网络请求
        }

        @Override
        public void onSuccess(String result) {
            if (result != null) {
                //如果走了cache方法返回了true, 将不再发起网络请求, 这里拿到的result就是null,
                MResponse mResponse = gson.fromJson(result, clazz);//按正常响应解析
                listener.onSuccess(mResponse, requestCode);
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            listener.onFailed(requestCode);
        }

        @Override
        public void onCancelled(CancelledException cex) {
        }

        @Override
        public void onFinished() {
        }
    });
    return cancelable;
}

/**
 * 异步post请求
 *
 * @param url
 * @param maps
 * @param requestCode
 * @param clazz
 * @param listener
 * @return
 */
public Callback.Cancelable post(String url, Map<String, String> maps, final int requestCode, final Class<? extends MResponse> clazz, final NetResponseListener listener) {
    RequestParams params = new RequestParams(url);
    if (maps != null && !maps.isEmpty()) {
        for (Map.Entry<String, String> entry : maps.entrySet()) {
            params.addBodyParameter(entry.getKey(), entry.getValue());
        }
    }

    Callback.Cancelable post = x.http().post(params, new Callback.CommonCallback<String>() {

        @Override
        public void onSuccess(String result) {
            MResponse mResponse = gson.fromJson(result, clazz);//按正常响应解析
            listener.onSuccess(mResponse, requestCode);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            listener.onFailed(requestCode);
        }

        @Override
        public void onCancelled(CancelledException cex) {
        }

        @Override
        public void onFinished() {

        }
    });
    return post;
}


/**
 * 文件上传
 *
 * @param url
 * @param maps
 * @param file
 * @param requestCode
 * @param clazz
 * @param listener
 * @return
 */
public Callback.Cancelable upLoadFile(String url, Map<String, String> maps, Map<String, File> file, final int requestCode, final Class<? extends MResponse> clazz, final NetUpLoadFileListener listener) {
    RequestParams params = new RequestParams(url);
    if (maps != null && !maps.isEmpty()) {
        for (Map.Entry<String, String> entry : maps.entrySet()) {
            params.addBodyParameter(entry.getKey(), entry.getValue());
        }
    }
    if (file != null && !maps.isEmpty()) {
        for (Map.Entry<String, File> entry : file.entrySet()) {
            params.addBodyParameter(entry.getKey(), entry.getValue().getAbsoluteFile());
        }
    }
    // 有上传文件时使用multipart表单, 否则上传原始文件流.
    params.setMultipart(true);//这个是标示上传的文件内容的,
    Callback.Cancelable cancelable = x.http().post(params, new Callback.ProgressCallback<String>() {

        @Override
        public void onSuccess(String result) {
            MResponse mResponse = gson.fromJson(result, clazz);//按正常响应解析
            listener.onSuccess(mResponse, requestCode);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            listener.onFailed(requestCode);
        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }

        @Override
        public void onWaiting() {

        }

        @Override
        public void onStarted() {

        }

        @Override
        public void onLoading(long total, long current, boolean isDownloading) {
            listener.onLoading(current, isDownloading, requestCode);
        }
    });

    return cancelable;
}

/**
 * 文件下载
 * @param url
 * @param filepath
 * @param requestCode
 * @param listener
 */
public void downLoadFile(String url, String filepath, final int requestCode, final NetDownLoadFileListener listener) {

    RequestParams params = new RequestParams(url);
    params.setAutoRename(true);// 断点续传, 也就是说支持中断之后再继续下载,
    params.setSaveFilePath(filepath);//设置文件保存的路径
    x.http().post(params, new Callback.ProgressCallback<File>() {
        @Override
        public void onSuccess(final File result) {
            listener.onSuccess(result, requestCode);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            listener.onFailed(requestCode);
        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {
        }

        @Override
        public void onWaiting() {

        }

        @Override
        public void onStarted() {

        }

        @Override
        public void onLoading(final long total, final long current, final boolean isDownloading) {
            listener.onLoading(current, isDownloading, requestCode);
        }
    });

}

}
还有一个GsonFormat之后的bean都要实现的一个接口
package com.diandou.bigdemo.utils.net;
public interface MResponse {
}

==========================================================
大家还要拿到cancle对象,神马的, 在封装baseActicity或者是BaseFragment在一起cancle掉网络请求, 这样放置奔溃哦

以上的普通的get.post网络请求, 还有文件上传和下载, 还有缓存实现, 大家如果还有需要的, 在去自行封装吧-_-

下面的这个是XUtils封装成的图片加载框架, 目前尚不算完善, 我会根据项目在去进行封装的, 要解决的有listview的view复用不让其混乱, 下拉刷新的时候让图片不要闪, 之后要做到的我在更新上来哦

import android.widget.ImageView;

import org.xutils.image.ImageOptions;
import org.xutils.x;

public class MImageLoaderUtil {
private volatile static MImageLoaderUtil instance;

/**
 * Double Check 单例模式
 *
 * @return
 */
public static MImageLoaderUtil getInstance() {
    if (instance == null) {
        synchronized (MImageLoaderUtil.class) {
            if (instance == null) {
                instance = new MImageLoaderUtil();
            }
        }
    }
    return instance;
}

public static void load(ImageView imageView, String url) {
    ImageOptions options = new ImageOptions.Builder().setAutoRotate(true)
            .setRadius(20)
            .setFadeIn(true)
            .setAutoRotate(true)
            .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
            .setUseMemCache(true).build();
    x.image().bind(imageView, url, options);
    //x.image().clearCacheFiles();//清楚图片缓存,

}

}

上一篇下一篇

猜你喜欢

热点阅读