欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android Xutils3网络请求的封装详解及实例代码

程序员文章站 2024-02-25 07:58:16
 xutils3网络请求的封装详解 封装了一个xutil3的网络请求工具类,分享给大家,本人水平有限,不足之处欢迎指出。 使用前先配置xutils3:...

 xutils3网络请求的封装详解

封装了一个xutil3的网络请求工具类,分享给大家,本人水平有限,不足之处欢迎指出。

使用前先配置xutils3:

1.gradle中添加

compile 'org.xutils:xutils:3.3.40'

2.自定义application

/**
 * created by joe on 2016/9/25.
 */
public class myapp extends application {
  @override
  public void oncreate() {
    super.oncreate();

    x.ext.init(this);
    x.ext.setdebug(buildconfig.debug); // 是否输出debug日志, 开启debug会影响性能.
  }
}

3.清单文件application节点点添加

 android:name=".activitys.myapp"

上面三步走完接下来就可以使用了

先写一个单利类,话不多说上代码

 private volatile static xutilshttp instance;
  private handler handler;
  private xutilshttp(){
    handler = new handler(looper.getmainlooper());
  }

  /**
   * 单利模式
   * @return
   */
  public static xutilshttp getinstance(){
    if (instance == null){
      synchronized (xutilshttp.class){
        if (instance == null){
          instance = new xutilshttp();
        }
      }
    }
    return instance;
  }

写好接口

 //接口回调
  public interface xcallback{
    void onresponse(string result);
    void onfail(string result);
  }
  //下载的接口回调
  public interface xdownloadcallback{
    void onstart();
    void onloading(long total,long current,boolean isdownloading);
    void onsuccess(file result);
    void onfail(string result);
    void onfinished();
  }

封装普通get请求

  /**
   * 普通get请求
   * @param url
   * @param maps
   * @param callback
   */
  public void get(string url, map<string,string> maps, final xcallback callback){
    requestparams params = new requestparams(url);
    if (null != maps && !maps.isempty()){
      for (map.entry<string,string> entry : maps.entryset()){
        params.addquerystringparameter(entry.getkey(),entry.getvalue());
      }
    }
    x.http().get(params, new callback.commoncallback<string>() {
      private boolean haserror = false;
      private string result = null;
      @override
      public void onsuccess(string result) {
        if (result != null) {
          this.result = result;
        }
      }

      @override
      public void onerror(throwable ex, boolean isoncallback) {
        haserror = true;
        toast.maketext(x.app(), ex.getmessage(), toast.length_long).show();
      }

      @override
      public void oncancelled(cancelledexception cex) {

      }

      @override
      public void onfinished() {
        if (!haserror && result != null) {
          onsuccessresponse(result,callback);
        }
      }
    });
  }

带缓存的get请求

 /**
   * 带缓存数据的异步get请求
   * @param url
   * @param maps
   * @param ifcache   是否缓存
   * @param cachetime  缓存存活时间
   * @param callback
   */
  public void getcache(string url,map<string,string> maps,final boolean ifcache,long cachetime,final xcallback callback){
    requestparams params = new requestparams(url);
    params.setcachemaxage(cachetime);
    if (null != maps && maps.isempty()){
      for (map.entry<string,string> entry : maps.entryset()){
        params.addquerystringparameter(entry.getkey(),entry.getvalue());
      }
    }
    x.http().get(params, new callback.cachecallback<string>() {
      private boolean haserror = false;
      private string result = null;
      @override
      public boolean oncache(string result) {
        if (ifcache && null != result){
          this.result = result;
        }
        // true: 信任缓存数据, 不在发起网络请求; false不信任缓存数据.
        return ifcache;
      }

      @override
      public void onsuccess(string result) {
        if (result != null) {
          this.result = result;
        }
      }

      @override
      public void onerror(throwable ex, boolean isoncallback) {
        haserror = true;
        toast.maketext(x.app(), ex.getmessage(), toast.length_long).show();
      }

      @override
      public void oncancelled(cancelledexception cex) {

      }

      @override
      public void onfinished() {
        if (!haserror && result != null) {
          onsuccessresponse(result,callback);
        }
      }
    });
  }

普通post请求

 /**
   * 异步post请求
   * @param url
   * @param maps
   * @param callback
   */
  public void post(string url, map<string,string> maps, final xcallback callback){
    requestparams params = new requestparams(url);
    if (null != maps && !maps.isempty()){
      for (map.entry<string,string> entry : maps.entryset()){
        params.addbodyparameter(entry.getkey(),entry.getvalue());
      }
    }
    x.http().post(params, new callback.commoncallback<string>() {
      private boolean haserror = false;
      private string result = null;
      @override
      public void onsuccess(string result) {
        if (result != null) {
          this.result = result;
        }
      }

      @override
      public void onerror(throwable ex, boolean isoncallback) {
        haserror = true;
        onfailresponse(ex.getmessage(),callback);
      }

      @override
      public void oncancelled(cancelledexception cex) {

      }

      @override
      public void onfinished() {
        if (!haserror && result != null) {
          onsuccessresponse(result,callback);
        }
      }
    });
  }

带缓存的post请求

  /**
   * 带缓存数据的异步post请求
   * @param url
   * @param maps
   * @param ifcache   是否缓存
   * @param cachetime  缓存存活时间
   * @param callback
   */
  public void postcache(string url,map<string,string> maps,final boolean ifcache,long cachetime,final xcallback callback){
    requestparams params = new requestparams(url);
    params.setcachemaxage(cachetime);
    if (null != maps && maps.isempty()){
      for (map.entry<string,string> entry : maps.entryset()){
        params.addbodyparameter(entry.getkey(),entry.getvalue());
      }
    }
    x.http().get(params, new callback.cachecallback<string>() {
      private boolean haserror = false;
      private string result = null;
      @override
      public boolean oncache(string result) {
        if (ifcache && null != result){
          this.result = result;
        }
        // true: 信任缓存数据, 不在发起网络请求; false不信任缓存数据.
        return ifcache;
      }

      @override
      public void onsuccess(string result) {
        if (result != null) {
          this.result = result;
        }
      }

      @override
      public void onerror(throwable ex, boolean isoncallback) {
        haserror = true;
        toast.maketext(x.app(), ex.getmessage(), toast.length_long).show();
      }

      @override
      public void oncancelled(cancelledexception cex) {

      }

      @override
      public void onfinished() {
        if (!haserror && result != null) {
          onsuccessresponse(result,callback);
        }
      }
    });
  }

文件的下载

  /**
   * 下载文件
   * @param url
   * @param filepath
   * @param callback
   */
  public void downfile(string url, string filepath, final xdownloadcallback callback){
    requestparams params = new requestparams(url);
    params.setsavefilepath(filepath);
    params.setautorename(true);
    x.http().get(params, new callback.progresscallback<file>() {
      @override
      public void onsuccess(final file result) {
        //下载完成会走该方法
        handler.post(new runnable() {
          @override
          public void run() {
            if (callback!=null){
              callback.onsuccess(result);
            }
          }
        });
      }
      @override
      public void onerror(final throwable ex, boolean isoncallback) {
        handler.post(new runnable() {
          @override
          public void run() {
            if (null != callback){
              callback.onfail(ex.getmessage());
            }
          }
        });
      }
      @override
      public void oncancelled(cancelledexception cex) {
      }
      @override
      public void onfinished() {
        handler.post(new runnable() {
          @override
          public void run() {
            if (callback!=null){
              callback.onfinished();
            }
          }
        });
      }
      //网络请求之前回调
      @override
      public void onwaiting() {
      }
      //网络请求开始的时候回调
      @override
      public void onstarted() {
        handler.post(new runnable() {
          @override
          public void run() {
            if (null != callback){
              callback.onstart();
            }
          }
        });
      }
      //下载的时候不断回调的方法
      @override
      public void onloading(final long total, final long current, final boolean isdownloading) {
        //当前进度和文件总大小
        handler.post(new runnable() {
          @override
          public void run() {
            if (callback!=null){
              callback.onloading(total,current,isdownloading);
            }
          }
        });
      }
    });
  }

文件的上传

  /**
   * 文件上传
   *
   * @param url
   * @param maps
   * @param file
   * @param callback
   */
  public void uploadfile(string url, map<string, string> maps, map<string, file> file, final xcallback callback) {
    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) {
      for (map.entry<string, file> entry : file.entryset()) {
        params.addbodyparameter(entry.getkey(), entry.getvalue().getabsolutefile());
      }
    }
    // 有上传文件时使用multipart表单, 否则上传原始文件流.
    params.setmultipart(true);
    x.http().post(params, new callback.commoncallback<string>() {
      @override
      public void onsuccess(string result) {
        onsuccessresponse(result, callback);
      }

      @override
      public void onerror(throwable ex, boolean isoncallback) {

      }

      @override
      public void oncancelled(cancelledexception cex) {

      }

      @override
      public void onfinished() {

      }
    });

  }

上传json字符串到服务器

  /**
   * 上传json串到服务器
   * @param url
   * @param maps 将需要传的各个参数放在map集合里面
   */
  public void uploadjson(string url, map<string, string> maps, final xcallback callback){
    jsonobject js_request = new jsonobject();//服务器需要传参的json对象
    try {
      for (map.entry<string,string> entry : maps.entryset()){
        js_request.put(entry.getkey(),entry.getvalue());
      }
    } catch (jsonexception e) {
      e.printstacktrace();
    }

    requestparams params = new requestparams(url);
    params.setasjsoncontent(true);
    params.setbodycontent(js_request.tostring());

    x.http().post(params, new callback.commoncallback<string>() {//发起传参为json的post请求,
      // callback.cachecallback<string>的泛型为后台返回数据的类型,
      // 根据实际需求更改
      private boolean haserror = false;
      private string result = null;

      @override
      public void onsuccess(string result) {
        if (result != null) {
          this.result = result;
        }
      }

      @override
      public void onerror(throwable ex, boolean isoncallback) {
        ex.printstacktrace();
      }

      @override
      public void oncancelled(cancelledexception cex) {

      }

      @override
      public void onfinished() {
        if (!haserror && result != null && callback!=null) {
          onsuccessresponse(result,callback);
        }
      }
    });

  }

使用案例:

下载调用:

   xutilshttp.getinstance().downfile(url, utils.getsdpath() + "/" + "shopbox_guide_video/" + utils.getfilename(url), new xutilshttp.xdownloadcallback() {

      @override
      public void onstart() {
        showdialog(dialog_download_progress);
      }

      @override
      public void onloading(long total, long current, boolean isdownloading) {
        //当前进度和文件总大小
        mprogressdialog.setmax((int) total);
        mprogressdialog.setprogress((int) current);
      }

      @override
      public void onsuccess(file result) {
        //下载完成会走该方法
        playmedia(result.getpath());
      }

      @override
      public void onfail(string result) {
        toast.maketext(mainactivity.this, result, toast.length_short).show();
      }

      @override
      public void onfinished() {
        dismissdialog(dialog_download_progress);
      }
    });

带缓存get请求

   xutilshttp.getinstance().postcache(url, null, true, 60000, new xutilshttp.xcallback() {
      @override
      public void onresponse(string result) {
        // 成功获取数据
      }

      @override
      public void onfail(string result) {
        toast.maketext(mainactivity.this, result, toast.length_short).show();
      }
    });

就是这么简单,不足之处请大家多多指点

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!