Browse Source

+ DefaultConvert 默认的转换器抽象
+ NetConfig.onError 网络错误信息回调
- Moshi依赖

drake 5 years ago
parent
commit
3a05bc244e

+ 1 - 1
README.md

@@ -54,7 +54,7 @@ allprojects {
 module of build.gradle
 
 ```groovy
-implementation 'com.github.liangjingkanji:Net:1.1.2'
+implementation 'com.github.liangjingkanji:Net:1.1.3'
 ```
 
 

+ 2 - 4
net/build.gradle

@@ -8,7 +8,7 @@ group = 'com.gitlab.liangjingkanji'
 
 android {
     compileSdkVersion 29
-    buildToolsVersion "29.0.0"
+    buildToolsVersion "29.0.2"
 
 
     defaultConfig {
@@ -38,11 +38,9 @@ dependencies {
     androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
 
     api 'com.yanzhenjie:okalle:0.1.7'
-    api 'com.squareup.moshi:moshi-kotlin:1.8.0'
-    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.8.0'
 
     compileOnly 'androidx.appcompat:appcompat:1.1.0'
-    compileOnly 'com.github.liangjingkanji:BRV:1.0.5'
+    compileOnly 'com.github.liangjingkanji:BRV:1.0.6'
     compileOnly 'io.reactivex.rxjava2:rxandroid:2.1.1'
 
 }

+ 1 - 1
net/proguard-rules.pro

@@ -1,5 +1,5 @@
 # Add project specific ProGuard rules here.
-# You can control the set of applied configuration files using the
+# You can control the setKalle of applied configuration files using the
 # proguardFiles setting in build.gradle.
 #
 # For more details, see

+ 11 - 7
net/src/main/java/com/drake/net/Net.kt

@@ -7,7 +7,7 @@
 
 package com.drake.net
 
-import com.drake.net.exception.ResponseException
+import com.drake.net.error.ResponseException
 import com.yanzhenjie.kalle.Kalle
 import com.yanzhenjie.kalle.download.UrlDownload
 import com.yanzhenjie.kalle.simple.SimpleBodyRequest
@@ -19,10 +19,11 @@ import io.reactivex.schedulers.Schedulers
 
 /**
  * Get请求
- * @param path String 默认加上Host
+ * @param path String 网络路径, 非绝对路径会加上HOST为前缀
+ * @see NetConfig.host
  * @param isAbsolutePath Boolean Path是否是绝对路径
  * @param block SimpleUrlRequest.Api.() -> UnitUtils
- * @return Observable<M>
+ * @return Observable<M> 结果会在主线程
  */
 inline fun <reified M> get(
     path: String,
@@ -59,10 +60,11 @@ inline fun <reified M> get(
 
 /**
  * Post提交
- * @param path String 默认加上Host
+ * @param path String 网络路径, 非绝对路径会加上HOST为前缀
+ * @see NetConfig.host
  * @param isAbsolutePath Boolean 是否是绝对路径
  * @param block SimpleBodyRequest.Api.() -> UnitUtils
- * @return Observable<M>
+ * @return Observable<M> 结果会在主线程
  */
 inline fun <reified M> post(
     path: String,
@@ -101,10 +103,12 @@ inline fun <reified M> post(
 /**
  * 下载文件
  *
- * @param path String 自动加上Host
+ * @param path String 网络路径, 非绝对路径会加上HOST为前缀
+ * @see NetConfig.host
  * @param directory String 下载文件存放目录 {默认存在android/data/packageName/cache目录}
  * @param isAbsolutePath Boolean 下载链接是否是绝对路径
- * @return Observable<String>
+ * @param block 请求参数
+ * @return Observable<String> 结果会在主线程
  */
 fun download(
     path: String,

+ 34 - 14
net/src/main/java/com/drake/net/NetConfig.kt

@@ -8,34 +8,54 @@
 package com.drake.net
 
 import android.app.Application
-import com.drake.net.convert.DefaultConverter
-import com.drake.net.listener.DefaultInterceptor
-import com.drake.net.listener.NetListener
+import android.widget.Toast
+import com.drake.net.error.ResponseException
 import com.yanzhenjie.kalle.Kalle
 import com.yanzhenjie.kalle.KalleConfig
+import com.yanzhenjie.kalle.exception.*
 
 
 object NetConfig {
 
     lateinit var host: String
     lateinit var app: Application
-    var listener: NetListener? = null
 
-    fun set(block: KalleConfig.Builder.() -> Unit) {
+
+    var onError: Throwable.() -> Unit = {
+
+        val message = when (this) {
+            is NetworkError -> app.getString(R.string.network_error)
+            is URLError -> app.getString(R.string.url_error)
+            is HostError -> app.getString(R.string.host_error)
+            is ConnectTimeoutError -> app.getString(R.string.connect_timeout_error)
+            is ConnectException -> app.getString(R.string.connect_exception)
+            is WriteException -> app.getString(R.string.write_exception)
+            is ReadTimeoutError -> app.getString(R.string.read_timeout_error)
+            is DownloadError -> app.getString(R.string.download_error)
+            is NoCacheError -> app.getString(R.string.no_cache_error)
+            is ParseError -> app.getString(R.string.parse_error)
+            is ReadException -> app.getString(R.string.read_exception)
+            is ResponseException -> msg
+            else -> {
+                printStackTrace()
+                app.getString(R.string.other_error)
+            }
+        }
+
+        Toast.makeText(app, message, Toast.LENGTH_SHORT).show()
+    }
+
+
+    fun setKalle(block: KalleConfig.Builder.() -> Unit) {
         val builder = KalleConfig.newBuilder()
         builder.block()
         Kalle.setConfig(builder.build())
     }
-}
 
-
-fun Application.setDefaultNetConfig(host: String, successCode: Int = 1) {
-    NetConfig.app = this
-    NetConfig.host = host
-
-    NetConfig.set {
-        addInterceptor(DefaultInterceptor())
-        converter(DefaultConverter(successCode))
+    // 处理错误信息
+    fun onError(block: Throwable.() -> Unit) {
+        onError = block
     }
 
+
 }

+ 26 - 27
net/src/main/java/com/drake/net/convert/DefaultConverter.kt

@@ -8,19 +8,24 @@
 package com.drake.net.convert
 
 import com.drake.net.NetConfig
-import com.squareup.moshi.Moshi
+import com.drake.net.R
 import com.yanzhenjie.kalle.Response
 import com.yanzhenjie.kalle.simple.Converter
 import com.yanzhenjie.kalle.simple.SimpleResponse
 import org.json.JSONException
 import org.json.JSONObject
-import java.io.IOException
 import java.lang.reflect.Type
 
 
+/**
+ * 默认的转换器要求数据结构为JSON对象
+ */
 @Suppress("UNCHECKED_CAST")
-class DefaultConverter(val successCode: Int = 1) :
-    Converter {
+abstract class DefaultConverter(
+    val successCode: String = "1",
+    val codeName: String = "code",
+    val msgName: String = "msg"
+) : Converter {
 
 
     @Throws(Exception::class)
@@ -33,41 +38,37 @@ class DefaultConverter(val successCode: Int = 1) :
         var succeedData: S? = null
         var failedData: F? = null
 
-        val json: String =
-            NetConfig.listener?.parse(response.body().string()) ?: response.body().string()
-
+        val body = response.body().string()
         var code = response.code()
 
         when {
             code in 200..299 -> {
                 try {
-                    val jsonObject = JSONObject(json)
-                    val responseCode = jsonObject.optInt("code")
+                    val jsonObject = JSONObject(body)
+                    val responseCode = jsonObject.optString(codeName)
 
                     if (responseCode == successCode) {
-                        run {
-                            if (succeed === String::class.java) {
-                                succeedData = json as S
-                            } else {
-                                try {
-                                    succeedData = MOSHI.adapter<S>(succeed).fromJson(json)
-                                } catch (e: IOException) {
-                                    e.printStackTrace()
-                                    failedData = "无法解析数据" as F
-                                }
+                        if (succeed === String::class.java) {
+                            succeedData = body as S
+                        } else {
+                            try {
+                                succeedData = convert(succeed, body)
+                            } catch (e: Exception) {
+                                e.printStackTrace()
+                                failedData = NetConfig.app.getString(R.string.parse_json_error) as F
                             }
                         }
                     } else {
-                        failedData = jsonObject.optString("errorMessage") as F
-                        code = responseCode
+                        failedData = jsonObject.optString(msgName) as F
+                        code = responseCode.toInt()
                     }
                 } catch (e: JSONException) {
                     e.printStackTrace()
-                    failedData = "无法解析错误信息" as F
+                    failedData = NetConfig.app.getString(R.string.parse_data_error) as F
                 }
             }
-            code in 400..499 -> failedData = "发生异常错误" as F
-            code >= 500 -> failedData = "服务器开小差啦" as F
+            code in 400..499 -> failedData = NetConfig.app.getString(R.string.request_error) as F
+            code >= 500 -> failedData = NetConfig.app.getString(R.string.server_error) as F
         }
 
         return SimpleResponse.newBuilder<S, F>().code(code)
@@ -78,8 +79,6 @@ class DefaultConverter(val successCode: Int = 1) :
             .build()
     }
 
-    companion object {
 
-        private val MOSHI = Moshi.Builder().build()
-    }
+    abstract fun <S> convert(succeed: Type, body: String): S
 }

+ 16 - 0
net/src/main/java/com/drake/net/error/ResponseException.kt

@@ -0,0 +1,16 @@
+/*
+ * Copyright (C) 2018, Umbrella CompanyLimited All rights reserved.
+ * Project:Net
+ * Author:Drake
+ * Date:9/16/19 12:54 AM
+ */
+
+package com.drake.net.error
+
+/**
+ *  对应网络请求后台定义的错误信息
+ * @property msg String 网络请求错误信息
+ * @property code Int 网络请求错误码
+ * @constructor
+ */
+class ResponseException(val msg: String, val code: Int) : Throwable()

+ 0 - 16
net/src/main/java/com/drake/net/exception/ResponseException.kt

@@ -1,16 +0,0 @@
-/*
- * Copyright (C) 2018, Umbrella CompanyLimited All rights reserved.
- * Project:Net
- * Author:Drake
- * Date:9/16/19 12:54 AM
- */
-
-package com.drake.net.exception
-
-/**
- *  对应网络请求后台定义的错误信息
- * @property errorMessage String 网络请求错误信息
- * @property errorCode Int 网络请求错误码
- * @constructor
- */
-class ResponseException(val errorMessage: String, val errorCode: Int) : Throwable()

+ 0 - 30
net/src/main/java/com/drake/net/listener/DefaultInterceptor.kt

@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2018, Umbrella CompanyLimited All rights reserved.
- * Project:Net
- * Author:Drake
- * Date:9/16/19 12:54 AM
- */
-
-package com.drake.net.listener
-
-import com.drake.net.NetConfig
-import com.yanzhenjie.kalle.Response
-import com.yanzhenjie.kalle.connect.Interceptor
-import com.yanzhenjie.kalle.connect.http.Chain
-import java.io.IOException
-
-/**
- * 响应体的日志打印器
- */
-class DefaultInterceptor : Interceptor {
-
-
-    @Throws(IOException::class)
-    override fun intercept(chain: Chain): Response {
-        val request = chain.request()
-        val response = chain.proceed(request)
-        NetConfig.listener?.net(request, response)
-        return response
-    }
-}
-

+ 0 - 17
net/src/main/java/com/drake/net/listener/NetListener.kt

@@ -1,17 +0,0 @@
-/*
- * Copyright (C) 2018, Umbrella CompanyLimited All rights reserved.
- * Project:Net
- * Author:Drake
- * Date:9/16/19 12:54 AM
- */
-
-package com.drake.net.listener
-
-import com.yanzhenjie.kalle.Request
-import com.yanzhenjie.kalle.Response
-
-interface NetListener {
-
-    fun net(request: Request, response: Response)
-    fun parse(body: String): String
-}

+ 2 - 1
net/src/main/java/com/drake/net/observer/DialogObserver.kt

@@ -15,6 +15,7 @@ import androidx.fragment.app.FragmentActivity
 import androidx.lifecycle.Lifecycle.Event
 import androidx.lifecycle.LifecycleObserver
 import androidx.lifecycle.OnLifecycleEvent
+import com.drake.net.NetConfig
 import io.reactivex.observers.DefaultObserver
 
 /**
@@ -78,7 +79,7 @@ abstract class DialogObserver<M>(
      */
     override fun onError(e: Throwable) {
         dismissDialog()
-        NetObserver.showErrorMsg(e)
+        NetConfig.onError.invoke(e)
     }
 
     override fun onComplete() {

+ 1 - 30
net/src/main/java/com/drake/net/observer/NetObserver.kt

@@ -7,14 +7,11 @@
 
 package com.drake.net.observer
 
-import android.widget.Toast
 import androidx.lifecycle.Lifecycle
 import androidx.lifecycle.LifecycleObserver
 import androidx.lifecycle.LifecycleOwner
 import androidx.lifecycle.OnLifecycleEvent
 import com.drake.net.NetConfig
-import com.drake.net.exception.ResponseException
-import com.yanzhenjie.kalle.exception.*
 import io.reactivex.observers.DefaultObserver
 
 
@@ -33,7 +30,7 @@ abstract class NetObserver<M>() : DefaultObserver<M>(), LifecycleObserver {
      * @param e 包括错误信息
      */
     override fun onError(e: Throwable) {
-        showErrorMsg(e)
+        NetConfig.onError.invoke(e)
     }
 
     override fun onComplete() {
@@ -44,30 +41,4 @@ abstract class NetObserver<M>() : DefaultObserver<M>(), LifecycleObserver {
     fun cancelRequest() {
         cancel()
     }
-
-    companion object {
-
-        fun showErrorMsg(e: Throwable) {
-            val message: String
-            when (e) {
-                is NetworkError -> message = "当前网络不可用"
-                is URLError -> message = "请求资源地址错误"
-                is HostError -> message = "无法找到指定服务器主机"
-                is ConnectTimeoutError -> message = "连接服务器超时,请重试"
-                is ConnectException -> message = "请检查网络连接"
-                is WriteException -> message = "发送数据错误"
-                is ReadTimeoutError -> message = "读取服务器数据超时,请检查网络"
-                is DownloadError -> message = "下载过程发生错误"
-                is NoCacheError -> message = "读取缓存错误"
-                is ParseError -> message = "解析数据时发生异常"
-                is ReadException -> message = "读取数据错误"
-                is ResponseException -> message = e.errorMessage
-                else -> {
-                    e.printStackTrace()
-                    message = "服务器未响应"
-                }
-            }
-            Toast.makeText(NetConfig.app, message, Toast.LENGTH_SHORT).show()
-        }
-    }
 }

+ 2 - 2
net/src/main/java/com/drake/net/observer/RefreshObserver.kt

@@ -10,6 +10,7 @@ package com.drake.net.observer
 import android.view.View
 import android.view.View.OnAttachStateChangeListener
 import com.drake.brv.PageRefreshLayout
+import com.drake.net.NetConfig
 import io.reactivex.observers.DefaultObserver
 
 /**
@@ -24,7 +25,6 @@ abstract class RefreshObserver<M>(val pageRefreshLayout: PageRefreshLayout) :
             override fun onViewAttachedToWindow(v: View) {
 
             }
-
             override fun onViewDetachedFromWindow(v: View) {
                 cancel()
             }
@@ -39,7 +39,7 @@ abstract class RefreshObserver<M>(val pageRefreshLayout: PageRefreshLayout) :
      */
     override fun onError(e: Throwable) {
         pageRefreshLayout.finish(false)
-        NetObserver.showErrorMsg(e)
+        NetConfig.onError.invoke(e)
     }
 
 

+ 23 - 0
net/src/main/res/values/strings.xml

@@ -1,3 +1,26 @@
 <resources>
     <string name="app_name">Net</string>
+
+
+    <!--网络请求异常-->
+    <string name="network_error">当前网络不可用</string>
+    <string name="url_error">请求资源地址错误</string>
+    <string name="host_error">无法找到指定服务器主机</string>
+    <string name="connect_timeout_error">连接服务器超时,请重试</string>
+    <string name="connect_exception">请检查网络连接</string>
+    <string name="write_exception">发送数据错误</string>
+    <string name="read_timeout_error">读取服务器数据超时,请检查网络</string>
+    <string name="download_error">下载过程发生错误</string>
+    <string name="no_cache_error">读取缓存错误</string>
+    <string name="parse_error">解析数据时发生异常</string>
+    <string name="read_exception">读取数据错误</string>
+    <string name="other_error">服务器未响应</string>
+
+    <!--DefaultConverter-->
+    <string name="parse_data_error">解析数据错误</string>
+    <string name="parse_json_error">解析JSON错误</string>
+    <string name="request_error">请求参数错误</string>
+    <string name="server_error">服务响应错误</string>
+
+
 </resources>

+ 6 - 2
sample/build.gradle

@@ -4,9 +4,11 @@ apply plugin: 'kotlin-android'
 
 apply plugin: 'kotlin-android-extensions'
 
+apply plugin: 'kotlin-kapt'
+
 android {
     compileSdkVersion 29
-    buildToolsVersion "29.0.0"
+    buildToolsVersion "29.0.2"
     defaultConfig {
         applicationId "com.drake.net.sample"
         minSdkVersion 19
@@ -34,5 +36,7 @@ dependencies {
     androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
     implementation project(path: ':net')
 
-    implementation 'com.github.liangjingkanji:BRV:1.0.5'
+    implementation 'com.squareup.moshi:moshi-kotlin:1.8.0'
+    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.8.0'
+    implementation 'com.github.liangjingkanji:BRV:1.0.6'
 }

+ 1 - 1
sample/proguard-rules.pro

@@ -1,5 +1,5 @@
 # Add project specific ProGuard rules here.
-# You can control the set of applied configuration files using the
+# You can control the setKalle of applied configuration files using the
 # proguardFiles setting in build.gradle.
 #
 # For more details, see

+ 0 - 10
sample/src/main/java/com/drake/net/sample/App.kt

@@ -1,20 +1,10 @@
 package com.drake.net.sample
 
 import android.app.Application
-import com.drake.net.setDefaultNetConfig
 
 class App : Application() {
 
     override fun onCreate() {
         super.onCreate()
-
-        setDefaultNetConfig("http://192.168.1.1")
-
-
-/*        // 设置默认的对话框
-        DialogObserver.setDefaultDialog {
-            val progressDialog = ProgressDialog(it)
-            progressDialog
-        }*/
     }
 }

+ 3 - 7
sample/src/main/res/layout/activity_main.xml

@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
@@ -9,10 +9,6 @@
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="Hello World!"
-        app:layout_constraintBottom_toBottomOf="parent"
-        app:layout_constraintLeft_toLeftOf="parent"
-        app:layout_constraintRight_toRightOf="parent"
-        app:layout_constraintTop_toTopOf="parent" />
+        android:text="Hello World!" />
 
-</androidx.constraintlayout.widget.ConstraintLayout>
+</LinearLayout>