Quellcode durchsuchen

提交添加拦截器功能,方式参数空指针后出现得ANR

sunqiang vor 1 Jahr
Ursprung
Commit
0f4f0e5458

+ 5 - 4
HttpCoreLibrary/src/main/java/com/rc/httpcore/HttpClient.kt

@@ -5,9 +5,7 @@ import com.rc.httpcore.client.factory.ClientFactory
 import com.rc.httpcore.client.factory.RetrofitFactory
 import com.rc.httpcore.config.OkHttpDNS
 import com.rc.httpcore.converter.NullOnEmptyConverterFactory
-import com.rc.httpcore.interceptor.HttpLoggingInterceptorLog
-import com.rc.httpcore.interceptor.NullToEmptyInterceptor
-import com.rc.httpcore.interceptor.TokenHeaderInterceptor
+import com.rc.httpcore.interceptor.*
 import okhttp3.OkHttpClient
 import okhttp3.logging.HttpLoggingInterceptor
 import retrofit2.Retrofit
@@ -70,7 +68,10 @@ object HttpClient {
             .connectTimeout(TIMEOUT_DEFAULT, TimeUnit.SECONDS) // 设置请求超时时间
             .writeTimeout(TIMEOUT_DEFAULT, TimeUnit.SECONDS) // 设置写入超时时间
             .addNetworkInterceptor(TokenHeaderInterceptor())
-            .addInterceptor(HttpLoggingInterceptorLog())//添加请求日志
+//            .addInterceptor(RequestInterceptor())
+            .addInterceptor(ParameterValidationInterceptor())
+            .addInterceptor(ResponseInterceptor())
+//            .addInterceptor(HttpLoggingInterceptorLog())//添加请求日志
 //            .addInterceptor(NullToEmptyInterceptor())//添加请求日志
             .retryOnConnectionFailure(true) // 设置出现错误进行重新连接
             .dns(OkHttpDNS())

+ 90 - 0
HttpCoreLibrary/src/main/java/com/rc/httpcore/interceptor/ParameterValidationInterceptor.kt

@@ -0,0 +1,90 @@
+package com.rc.httpcore.interceptor
+
+import android.annotation.SuppressLint
+import android.util.Log
+import okhttp3.Interceptor
+import okhttp3.Response
+import okhttp3.ResponseBody
+import okio.Buffer
+import org.json.JSONObject
+import java.io.IOException
+
+class ParameterValidationInterceptor : Interceptor {
+    companion object {
+        private const val TAG = "ParameterValidationInterceptor"
+    }
+    @SuppressLint("LongLogTag")
+    override fun intercept(chain: Interceptor.Chain): Response {
+        val request = chain.request()
+
+        // 检查查询参数
+        val originalUrl = request.url()
+        Log.d(TAG, "Request parameters: $originalUrl")
+        // 创建一个新的请求体,便于后续使用
+        val requestBody = request.body()
+        val buffer = Buffer()
+        requestBody?.writeTo(buffer)
+
+        // 获取请求体的字符串形式(假设为 JSON)
+        val requestBodyString = buffer.readUtf8()
+
+        // 建立一个标志来跟踪是否有空参数
+        val hasEmptyParameter = StringBuilder()
+        val queryParametersLog = StringBuilder()
+        val bodyParametersLog = StringBuilder()
+
+        // 检查请求体(例如,POST 请求)
+        if (request.method() == "POST" && requestBody != null) {
+            try {
+                val jsonParams = JSONObject(requestBodyString)
+                jsonParams.keys().forEach { key ->
+                    val value = jsonParams.optString(key)
+                    if (value.isEmpty()) {
+                        hasEmptyParameter.append("Body parameter '$key' is empty; ")
+                    } else {
+                        bodyParametersLog.append("Body parameter '$key': $value; ")
+                    }
+                }
+            } catch (e: Exception) {
+                Log.e(TAG, "Failed to parse request body as JSON: ${e.message}")
+            }
+        }
+
+        if (originalUrl.queryParameterNames().isNotEmpty()) {
+            for (name in originalUrl.queryParameterNames()) {
+                val value = originalUrl.queryParameter(name)
+                if (value.isNullOrEmpty()) {
+                    hasEmptyParameter.append("Query parameter '$name' is empty; ")
+                } else {
+                    queryParametersLog.append("Query parameter '$name': $value; ")
+                }
+            }
+        }
+
+        // 打印所有请求参数(合并为一行)
+        Log.d(TAG, "Request parameters: ${queryParametersLog.toString()}${bodyParametersLog.toString()}")
+
+
+        // 打印空参数信息
+        if (hasEmptyParameter.isNotEmpty()) {
+            Log.e(TAG, "Request contains empty parameters: $hasEmptyParameter")
+        }
+
+        // 继续处理请求
+        val response = chain.proceed(request)
+
+        // 读取响应体
+        val responseBody = response.body()
+        val responseBodyString = responseBody?.string() ?: ""
+
+        // 打印返回值日志
+        Log.d(TAG, "Response: $responseBodyString")
+
+        // 创建一个新的响应体,以便返回
+        return response.newBuilder()
+            .body(ResponseBody.create(responseBody?.contentType(), responseBodyString))
+            .build()
+    }
+
+
+}

+ 103 - 0
HttpCoreLibrary/src/main/java/com/rc/httpcore/interceptor/RequestInterceptor.kt

@@ -0,0 +1,103 @@
+package com.rc.httpcore.interceptor
+
+import android.util.Log
+import com.google.gson.Gson
+import com.google.gson.JsonObject
+import okhttp3.*
+import okio.Buffer
+import java.io.IOException
+
+class RequestInterceptor : Interceptor {
+    private val gson = Gson()
+    private val TAG = "RequestInterceptor" // 日志标签
+
+    override fun intercept(chain: Interceptor.Chain): Response {
+        // 获取原始请求
+        val originalRequest: Request = chain.request()
+
+        // 处理不同类型的请求
+        return when (originalRequest.method()) {
+            "GET" -> handleGetRequest(originalRequest, chain)
+            "POST" -> handlePostRequest(originalRequest, chain)
+            else -> chain.proceed(originalRequest) // 对于其他请求方法,直接执行
+        }
+    }
+
+    private fun handleGetRequest(request: Request, chain: Interceptor.Chain): Response {
+        val response = chain.proceed(chain.request())
+        val mediaType = response.body()!!.contentType()
+        val content = response.body()!!.string()
+        // 获取 URL 查询参数
+        val url = request.url()
+        val jsonParams = JsonObject()
+        // 检查查询参数是否为空
+        if (url.queryParameterNames().isEmpty()) {
+            Log.d(TAG, "GET Request: ${request.url()}, No query parameters.")
+        } else {
+            // 将查询参数解析为 JsonObject
+            for (name in url.queryParameterNames()) {
+                val value = url.queryParameter(name)
+                if (value != null) {
+                    jsonParams.addProperty(name, value)
+                } else {
+                    jsonParams.addProperty(name, "default_value") // 可选:处理空值的默认值
+                }
+            }
+
+            // 日志输出 GET 请求及其参数
+            Log.d(TAG, "GET Request: ${request.url()}")
+            Log.d(TAG, "GET Request: Params: ${gson.toJson(jsonParams)}")
+            Log.d(TAG, "GET Request: Params: $content")
+        }
+
+        return response.newBuilder()
+            .body(ResponseBody.create(mediaType, content))
+            .build()
+    }
+
+    private fun handlePostRequest(request: Request, chain: Interceptor.Chain): Response {
+        val response = chain.proceed(chain.request())
+        val mediaType = response.body()!!.contentType()
+        val content = response.body()!!.string()
+        // 获取请求体并转换为字符串
+        val requestBody = request.body() ?: throw IOException("Request body cannot be null")
+        val jsonString = requestBodyToString(requestBody) ?: throw IOException("Request parameters cannot be null or empty")
+
+        // 解析 JSON 并处理空值
+        val jsonObject = gson.fromJson(jsonString, JsonObject::class.java)
+        val fillDefaultValues = fillDefaultValues(jsonObject)
+
+        // 创建新的请求体
+        val modifiedRequestBody = RequestBody.create(requestBody.contentType(), gson.toJson(jsonObject))
+
+        // 构建新的请求
+        val modifiedRequest = request.newBuilder()
+            .method(request.method(), modifiedRequestBody)
+            .header("Authorization", "Bearer your_token_here") // 可选:添加认证头
+            .build()
+
+        // 日志输出 POST 请求
+        Log.d(TAG, "POST Request: ${modifiedRequest.url()}, Body: ${gson.toJson(jsonObject)}")
+
+        return response.newBuilder()
+            .body(ResponseBody.create(mediaType, gson.toJson(jsonObject)))
+            .build()
+    }
+
+    private fun requestBodyToString(body: RequestBody): String? {
+        val buffer = Buffer()
+        body.writeTo(buffer)
+        return buffer.readUtf8()
+    }
+
+    private fun fillDefaultValues(jsonObject: JsonObject): String {
+        // 遍历 JSON 对象并替换空值
+        for ((key, value) in jsonObject.entrySet()) {
+            if (value.isJsonNull || (value.isJsonPrimitive && value.asJsonPrimitive.isString && value.asString.isEmpty())) {
+                jsonObject.addProperty(key, "default_value") // 设置默认值
+            }
+        }
+        // 返回更新后的 JSON 字符串
+        return gson.toJson(jsonObject)
+    }
+}

+ 17 - 0
HttpCoreLibrary/src/main/java/com/rc/httpcore/interceptor/ResponseInterceptor.kt

@@ -0,0 +1,17 @@
+package com.rc.httpcore.interceptor
+
+import android.util.Log
+import okhttp3.Interceptor
+import okhttp3.Response
+import java.io.IOException
+
+class ResponseInterceptor : Interceptor {
+    override fun intercept(chain: Interceptor.Chain): Response {
+        Log.d("====ResponseInterceptor","拦截器")
+        val response = chain.proceed(chain.request())
+        if (!response.isSuccessful || response.body() == null) {
+            throw IOException("Response failed or body is null")
+        }
+        return response
+    }
+}

+ 1 - 1
HttpCoreLibrary/src/main/java/com/rc/httpcore/interceptor/TokenHeaderInterceptor.kt

@@ -10,6 +10,7 @@ import com.rc.httpcore.vo.CommonResponse
 import okhttp3.Interceptor
 import okhttp3.Request
 import okhttp3.Response
+import java.io.IOException
 import java.lang.Exception
 import java.nio.charset.StandardCharsets
 
@@ -19,7 +20,6 @@ class TokenHeaderInterceptor : Interceptor {
     override fun intercept(chain: Interceptor.Chain): Response {
         val originalRequest: Request = chain.request()
         val requestBuilder: Request.Builder = originalRequest.newBuilder()
-
         if (!HttpClient.token.isNullOrEmpty()) {
             requestBuilder.addHeader("authorization", HttpClient.token!!)
             Log.d("===========",HttpClient.token!!)

+ 70 - 68
app/src/main/java/com/example/chemical/ui/newly/AddedChemicalsActivity.kt

@@ -593,18 +593,20 @@ class AddedChemicalsActivity : BaseCountDownActivity<ActivityAddedChemicalsBindi
     }
 
     private fun getControlConfigs(chemicalNumber: String) {
+
         showLoading("提交中...")
         val disposable = ApiRepository.controlConfigs(modelA.chemicalLevel)
                 .subscribe({ data ->
                     dismissLoading()
                     mChemicalConfsBean = data
-//                searchProducer()
+                    //                searchProducer()
                     certitude(chemicalNumber)
                 }, { throwable ->
                     showNetError(throwable)
                     dismissLoading()
                 })
         addDisposable(disposable)
+
     }
 
     private fun getCheckRfids(rfid: String, tagCode: String, wxCode: String, position: Int) {
@@ -1050,88 +1052,88 @@ class AddedChemicalsActivity : BaseCountDownActivity<ActivityAddedChemicalsBindi
     }
 
 
-    private suspend  fun  connectToDeviceWithTimeout() {
+    private suspend fun connectToDeviceWithTimeout() {
         showToast("连接中...", Toast.LENGTH_SHORT)
 //        lifecycleScope.launch {
 
-            val deviceAddress = withContext(Dispatchers.IO) {
-                BluetoothConnectionManager.getDeviceAddress()
+        val deviceAddress = withContext(Dispatchers.IO) {
+            BluetoothConnectionManager.getDeviceAddress()
+        }
+        if (deviceAddress != null) {
+            val socket = withContext(Dispatchers.IO) {
+                BluetoothConnectionManager.connectToDevice(deviceAddress)
             }
-            if (deviceAddress != null) {
-                val socket = withContext(Dispatchers.IO) {
-                    BluetoothConnectionManager.connectToDevice(deviceAddress)
-                }
-                if (socket != null) {
-                    // 连接成功后的处理逻辑
-                    // 在这里使用返回的 BluetoothSocket 对象进行后续操作
-                    MediaPlayerHelper.playRawMp3(
-                            this@AddedChemicalsActivity,
-                            R.raw.qing_zheng_zhong
-                    )
+            if (socket != null) {
+                // 连接成功后的处理逻辑
+                // 在这里使用返回的 BluetoothSocket 对象进行后续操作
+                MediaPlayerHelper.playRawMp3(
+                        this@AddedChemicalsActivity,
+                        R.raw.qing_zheng_zhong
+                )
 //                    showToast("连接成功", Toast.LENGTH_SHORT)
-                    // 连接成功后的处理逻辑
-                    // 切换回主线程更新 UI
-                    withContext(Dispatchers.Main) {
-                        do {
-                            val inputStream = socket!!.inputStream
-                            val bt = ByteArray(1024)
-                            val content = inputStream!!.read(bt)
-                            if (content != null && content > 0) {
-                                val contents = String(
-                                        bt,
-                                        0,
-                                        content,
-                                        StandardCharsets.UTF_8
-                                )
-                                val split = contents.split("\n")
-                                val weight = split[0].trim()
-                                RcLog.info("===================称重未处理之前=======$contents")
-                                RcLog.info("===================weight=======$weight")
-                                RcLog.info("=====称重数据$weight $taskStarted  ${mWeighingValue!!.text.toString()}")
-                                if (weight.toDouble() > 2999) {
-                                    turnOffWeighing()
-                                } else {
-                                    if (weight.toDouble() > 0) {
-                                        if (mWeighingValue!!.text.toString().trim()
-                                                        .isNotEmpty()
+                // 连接成功后的处理逻辑
+                // 切换回主线程更新 UI
+                withContext(Dispatchers.Main) {
+                    do {
+                        val inputStream = socket!!.inputStream
+                        val bt = ByteArray(1024)
+                        val content = inputStream!!.read(bt)
+                        if (content != null && content > 0) {
+                            val contents = String(
+                                    bt,
+                                    0,
+                                    content,
+                                    StandardCharsets.UTF_8
+                            )
+                            val split = contents.split("\n")
+                            val weight = split[0].trim()
+                            RcLog.info("===================称重未处理之前=======$contents")
+                            RcLog.info("===================weight=======$weight")
+                            RcLog.info("=====称重数据$weight $taskStarted  ${mWeighingValue!!.text.toString()}")
+                            if (weight.toDouble() > 2999) {
+                                turnOffWeighing()
+                            } else {
+                                if (weight.toDouble() > 0) {
+                                    if (mWeighingValue!!.text.toString().trim()
+                                                    .isNotEmpty()
+                                    ) {
+                                        if (weight.toDouble() == mWeighingValue!!.text.toString()
+                                                        .trim().toDouble()
                                         ) {
-                                            if (weight.toDouble() == mWeighingValue!!.text.toString()
-                                                            .trim().toDouble()
-                                            ) {
-                                                if (taskStarted == false) {
-                                                    taskStarted = true
-                                                    RcLog.info("=====执行了")
-                                                    socket.close()
-                                                    delayedTaskToUpdateUI()
-                                                    break
-                                                }
+                                            if (taskStarted == false) {
+                                                taskStarted = true
+                                                RcLog.info("=====执行了")
+                                                socket.close()
+                                                delayedTaskToUpdateUI()
+                                                break
                                             }
                                         }
-                                        mWeighingValue!!.setText("$weight")
-                                    } else {
-                                        mWeighingValue!!.setText("")
                                     }
+                                    mWeighingValue!!.setText("$weight")
+                                } else {
+                                    mWeighingValue!!.setText("")
                                 }
-                                RcLog.info("==========蓝牙称 内存测试")
-                                delay(200)
-                            } else {
-                                showToast("请手动输入")
-                                weiView()
-                                break
                             }
-                        } while (true)
-                    }
-
-                } else {
-                    // 连接失败的处理逻辑
-                    showToast("连接失败或超时", Toast.LENGTH_SHORT)
-                    weiView()
+                            RcLog.info("==========蓝牙称 内存测试")
+                            delay(200)
+                        } else {
+                            showToast("请手动输入")
+                            weiView()
+                            break
+                        }
+                    } while (true)
                 }
+
             } else {
-                // 根据设备名称获取的设备地址为空,处理无法找到设备的情况
-                showToast("找不到设备", Toast.LENGTH_SHORT)
+                // 连接失败的处理逻辑
+                showToast("连接失败或超时", Toast.LENGTH_SHORT)
                 weiView()
             }
+        } else {
+            // 根据设备名称获取的设备地址为空,处理无法找到设备的情况
+            showToast("找不到设备", Toast.LENGTH_SHORT)
+            weiView()
+        }
 //        }
 
     }