kotlin中使用 xUtils 是轻量级网络请求工具

kotlin中使用 xUtils 轻量级网络请求工具:

xUtils 包含了orm, http(s), image, view注解, 但依然很轻量级(251K), 并且特性强大, 看看官网就知道了
git地址: https://github.com/Jay-YaoJie/xUtils3
kotlin中使用 xUtils 是轻量级网络请求工具_第1张图片

项目中快速配置xUtils3

  1. 使用Gradle构建时添加一下依赖即可
 // 最新的包引用可以去查看 http://jcenter.bintray.com/org/xutils/xutils/
  implementation 'org.xutils:xutils:3.7.6'
  1. 加入网络请求权限
 
 
  1. 在Application初始化
  // 这一步之后, 我们就可以在任何地方使用x.app()来获取Application的实例了.
  x.Ext.init(this); 
  // 是否输出debug日志, 开启debug会影响性能.
  x.Ext.setDebug(false);

xUtils3主要包含注解模块、网络模块、图片模块和数据库模块,下面我做了网络模块的工具,可以直接使用在项目中

package com.hldm.lbtafxapp.utils

import android.os.Environment
import com.yzb.lbtafxapp.FileKt.LogUtils
import com.yzb.lbtafxapp.utils.ToastUtil
import org.xutils.common.Callback
import org.xutils.http.RequestParams
import org.xutils.x
import java.io.File
import org.xutils.common.task.PriorityExecutor


/**
 * author : Jeff  [email protected]
 * Csdn :https://blog.csdn.net/Jeff_YaoJie
 * Github: https://github.com/Jay-YaoJie
 * Created :  2019-09-21.
 * description : xUtils3网络模块的使用
 * https://github.com/Jay-YaoJie/xUtils3
 *
 */
object xHttpUtil {
    val tag: String = "xHttpUtil"
    var call: Callback.Cancelable? = null
    /**
     * GET异步请求
     * @param RequestParams: params
     *      val params = RequestParams(url)
    params.addQueryStringParameter("username", "abc")
    params.addQueryStringParameter("password", "123")
     * @param callback: xCallback
     */
    open fun get_Async(params: RequestParams, callback: xCallback) {
//        val params = RequestParams(url)
//        params.addQueryStringParameter("username", "abc")
//        params.addQueryStringParameter("password", "123")

// 默认缓存存活时间, 单位:毫秒(如果服务器没有返回有效的max-age或Expires则参考)
        params.cacheMaxAge = (1000 * 60).toLong()
        call = x.http().get(params, object : Callback.CacheCallback {
            private var hasError = false
            private var result: Any? = null
            override fun onCache(result: String): Boolean { //得到缓存数据, 缓存过期后不会进入
                this.result = result
                return true //true: 信任缓存数据, 不再发起网络请求; false不信任缓存数据
            }

            override fun onSuccess(result: String?) {
                //如果服务返回304或onCache选择了信任缓存,这时result为null
                //  LogUtils.i("JAVA", "开始请求")
                if (result != null) {
                    this.result = result
                }
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                ex.printStackTrace()
                hasError = true
            }

            override fun onCancelled(cex: Callback.CancelledException) {
                cex.printStackTrace()
                hasError = true
            }

            override fun onFinished() {
                if (!hasError && result != null) {
                    //成功获取数据
                    LogUtils.d(tag, result.toString())
                    callback.onResponse(result!!)

                } else {
                    callback.onError()
                    ToastUtil.show("网络异常,请稍后重试!")
                }
            }
        })
    }

    /**
     * POST异步请求
     * @param RequestParams: params
     *   val params = RequestParams(url)
    params.addBodyParameter("username", "abc")
    params.addParameter("password", "123")
    params.addHeader("head", "android") //为当前请求添加一个头
     * @param callback: xCallback
     */
    fun post_Async(params: RequestParams, callback: xCallback) {
//        val params = RequestParams(url)
//        params.addBodyParameter("username", "abc")
//        params.addParameter("password", "123")
//        params.addHeader("head", "android") //为当前请求添加一个头
        call = x.http().post(params, object : Callback.CommonCallback {
            private var result: Any? = null
            private var hasError = false
            override fun onSuccess(result: String) {
                //解析result
                this.result = result
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                ex.printStackTrace()
                hasError = true
            }

            override fun onCancelled(cex: Callback.CancelledException) {
                cex.printStackTrace()
                hasError = true
            }

            override fun onFinished() {
                if (!hasError && result != null) {
                    //成功获取数据
                    LogUtils.d(tag, result.toString())
                    callback.onResponse(result!!)

                } else {
                    callback.onError()
                    ToastUtil.show("网络异常,请稍后重试!")
                }
            }
        })

    }
    /**
     * 文件下载
     * @param RequestParams: params
     *     val params = RequestParams(url)
    params.addBodyParameter("username", "abc")
    params.addParameter("password", "123")
    params.addHeader("head", "android") //为当前请求添加一个头
    val path = "/mnt/sdcard/Download/icon.jpg"
    params.isMultipart = true
    params.addBodyParameter("file", File(path))
     * @param callback: xCallback
     */
    fun post_UploadFile(params: RequestParams, callback: xCallback){
//        val params = RequestParams(url)
//        params.addBodyParameter("username", "abc")
//        params.addParameter("password", "123")
//        params.addHeader("head", "android") //为当前请求添加一个头
//        val path = "/mnt/sdcard/Download/icon.jpg"
//        params.isMultipart = true
//        params.addBodyParameter("file", File(path))
        x.http().post(params, object : Callback.CommonCallback {
            private var result: Any? = null
            private var hasError = false
            override fun onSuccess(result: String) {
                //上传完成
                this.result = result
            }
            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                ex.printStackTrace()
                hasError = true
            }
            override fun onCancelled(cex: Callback.CancelledException) {
                cex.printStackTrace()
                hasError = true
            }
            override fun onFinished() {
                if (!hasError && result != null) {
                    //成功获取数据
                    LogUtils.d(tag, result.toString())
                    callback.onResponse(result!!)

                } else {
                    callback.onError()
                    ToastUtil.show("网络异常,请稍后重试!")
                }
            }
        })
    }
    /**
     * 文件下载
     * @param RequestParams: params
     *    val params = RequestParams("http://127.0.0.1/server/abc.apk")
    自定义保存路径,Environment.getExternalStorageDirectory():SD卡的根目录
    params.saveFilePath = Environment.getExternalStorageDirectory() + "/myapp/"
    自动为文件命名
    params.isAutoRename = true
    params.addBodyParameter("username", "abc")
    params.addParameter("password", "123")
    params.addHeader("head", "android") //为当前请求添加一个头
     * @param callback: xCallback
     */
    fun post_LoadFile(params: RequestParams, callback: xCallback) {

//        val params = RequestParams("http://127.0.0.1/server/abc.apk")
        //        params.addBodyParameter("username", "abc")
//        params.addParameter("password", "123")
//        params.addHeader("head", "android") //为当前请求添加一个头
//        //自定义保存路径,Environment.getExternalStorageDirectory():SD卡的根目录
//        params.saveFilePath = Environment.getExternalStorageDirectory() + "/myapp/"
//        //自动为文件命名
//        params.isAutoRename = true
        call = x.http().post(params, object : Callback.ProgressCallback {
            private var result: Any? = null
            private var hasError = false
            override fun onSuccess(result: File) {
                //下载完成
                this.result = result
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                ex.printStackTrace()
                hasError = true
            }

            override fun onCancelled(cex: Callback.CancelledException) {
                cex.printStackTrace()
                hasError = true
            }

            override fun onFinished() {
                if (!hasError && result != null) {
                    //成功获取数据
                    LogUtils.d(tag, result.toString())
                    callback.onResponse(result!!)

                } else {
                    callback.onError()
                    ToastUtil.show("网络异常,请稍后重试!")
                }
            }

            //网络请求之前回调
            override fun onWaiting() {}

            //网络请求开始的时候回调
            override fun onStarted() {}

            //下载的时候不断回调的方法
            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                //当前进度和文件总大小
                LogUtils.i(tag, "current:$current,total:$total")
            }
        })
    }

    /**
     * 文件下载
     * @param RequestParams: params
     *     val params = RequestParams(pathApk)
     * @param callback: xCallback
     */
    fun get_LoadFile(params: RequestParams, callback: xCallback): Callback.Cancelable? {
        //设置请求参数
        //val params = RequestParams(pathApk)
        params.isAutoResume = true//设置是否在下载是自动断点续传
        params.isAutoRename = true//设置是否根据头信息自动命名文件
        // params.saveFilePath = "/sdcard/xutils/xUtils_1.avi"
        params.executor = PriorityExecutor(2, true)//自定义线程池,有效的值范围[1, 3], 设置为3时, 可能阻塞图片加载.
        params.isCancelFast = true//是否可以被立即停止.
        //下面的回调都是在主线程中运行的,这里设置的带进度的回调
        call = x.http().get(params, object : Callback.ProgressCallback {
            private var result: Any? = null
            private var hasError = false
            override fun onCancelled(cex: Callback.CancelledException) {
                // Log.i("tag", "取消" + Thread.currentThread().name)
                cex.printStackTrace()
                hasError = true
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                //   Log.i("tag", "onError: 失败" + Thread.currentThread().name)
                //   progressDialog.dismiss()
                ex.printStackTrace()
                hasError = true
            }

            override fun onFinished() {
                // Log.i("tag", "完成,每次取消下载也会执行该方法" + Thread.currentThread().name)
                //  progressDialog.dismiss()
                if (!hasError && result != null) {
                    //成功获取数据
                    LogUtils.d(tag, result.toString())
                    callback.onResponse(result!!)

                } else {
                    callback.onError()
                    ToastUtil.show("网络异常,请稍后重试!")
                }
            }

            override fun onSuccess(result: File) {
                //  Log.i("tag", "下载成功的时候执行" + Thread.currentThread().name)
                this.result = result
            }

            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                if (isDownloading) {
                    //     progressDialog.setProgress((current * 100 / total).toInt())
                    //   Log.i("tag", "下载中,会不断的进行回调:" + Thread.currentThread().name)
                    //当前进度和文件总大小
                    LogUtils.i(tag, "current:$current,total:$total")
                }
            }

            override fun onStarted() {
                // Log.i("tag", "开始下载的时候执行" + Thread.currentThread().name)
                // progressDialog.show()
            }

            override fun onWaiting() {
                //   Log.i("tag", "等待,在onStarted方法之前执行" + Thread.currentThread().name)
            }

        })
        return call
    }


    interface xCallback {
        fun onResponse(result: Any)
        fun onError() {
            //取消请求
//            if (call!==null){
//                call!!.cancel();
//            }

        }
    }

}

你可能感兴趣的:(Kotlin,Android)