⑤ 自定义后拦截器
对响应数据进行处理,如字符串解析显示
class SimpleParsingInterceptor: Interceptor { override fun intercept(chain: Interceptor.Chain): Task { val task = chain.task() if(task is ImageTask) { task.response?.let { var tempContent = it.content if(tempContent.startsWith("{")) { val index: Int = tempContent.indexOf("{") tempContent = tempContent.substring(index) } try { val jsonObject = JSONObject(tempContent) if (jsonObject.getInt("code") == 200) { //解析服务端回传内容 val mapJson: JSONObject = jsonObject.getJSONObject("data") var key = "" var image = "" val ite = mapJson.keys() while (ite.hasNext()) { key = ite.next() image = mapJson[key] as String } task.fileUrl = image task.fileUrl?.logV() } else { jsonObject.toString().logV() } } catch (e: Exception) { e.message?.logD() } } } return chain.proceed(task) } }
⑥ 初始化
可以不在App类中初始化,只要保证在upload前init()了就行~
LightUpload.init(LightUploadBuilder() // 传入默认配置,可变参数,支持多种类型Task的定制 .config(LightUploadTask.IMAGE to ImageUploadConfig().apply { reqData = ReqData( uploadUrl = "http://127.0.0.1:5000/upload", requestMethod = "POST", headers = hashMapOf( "Charset" to "utf-8", "connection" to "keep-alive" ) ) }, LightUploadTask.VIDEO to VideoUploadConfig() .apply { reqData = ReqData( uploadUrl = "http://127.0.0.1:5000/upload", requestMethod = "POST", headers = hashMapOf( "Charset" to "utf-8", "connection" to "keep-alive" ) ) }) // 设置上传请求,同样也是可变参数,支持多种类型定制 .upload(LightUploadTask.IMAGE to HucUpload()) // 添加前拦截器 .addBeforeInterceptor(PictureRotateInterceptor()) .addBeforeInterceptor(PictureCompressInterceptor()) .addBeforeInterceptor(VideoCompressInterceptor()) .addBeforeInterceptor(VideoFrameInterceptor()) // 添加后拦截器 .addDoneInterceptors(SimpleParsingInterceptor()) )
⑦ 调用上传
LightUpload.upload(task = CpImageTask().apply { filePath = path needCompress = true compressPercent = (1..100).random() callback = object : Upload.CallBack { override fun onSuccess(task: Task) { // 成功回调 text = " ${task.response!!.content}\n" } override fun onFailure(task: Task) { // 失败回调 task.throwable?.message?.let { it1 -> shortToast(it1) } } } })
0x5、Demo测试
命令行cd到项目的upload-server项目,第一次运行前执行下述命令安装python脚本相关依赖:
pip install -r pip install requirements.txt
安装完后,键入下述命令运行脚本:
python app.py
然后手机和电脑在同一局域网,配置下代理,输入ipconfig查看本机IP
网络异常,图片无法展示
|
配置下手机,开下charles:
网络异常,图片无法展示
|
运行效果如下:
网络异常,图片无法展示
|
Logcat也可以看到输出信息:
网络异常,图片无法展示
|
Nice~