Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Xutils3網絡請求的封裝詳解及實例代碼

Android Xutils3網絡請求的封裝詳解及實例代碼

編輯:關於Android編程

 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();
      }
    });

就是這麼簡單,不足之處請大家多多指點

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved