新接口调试

This commit is contained in:
2026-01-29 18:51:42 +08:00
parent 3d28c5692a
commit a4905e7226
50 changed files with 1753 additions and 1716 deletions
@@ -0,0 +1,118 @@
package com.shuwei.dish.match.net
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toType
import org.apache.http.conn.ConnectTimeoutException
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
///**
// * 通用网络请求封装,统一处理异常
// * @param onRequest 实际的 Retrofit 接口请求
// * @param onSuccess 成功回调
// * @param onFailure 自定义错误回调(可选,不传则用默认提示)
// */
//suspend fun <T> apiRequest(
// onRequest: suspend () -> T,
// onSuccess: (T) -> Unit,
// onFailure: ((ApiException) -> Unit)? = null
//) {
// try {
// // 执行实际的网络请求
// val result = onRequest()
// onSuccess(result)
// } catch (e: Exception) {
// val apiException = getApiException(e)
// // 优先执行自定义错误回调,没有则用默认提示
// if (onFailure != null) {
// onFailure(apiException)
// } else {
// // 默认的错误提示(可根据 ErrorType 定制)
// val tip = apiException.errorMsg
// // 切换到UI线程弹提示(用 MainScope 确保在主线程)
// MainScope().launch {
// BaseApp.instance?.toast(tip)
// }
// }
// }
//}
/**
* 通用网络请求封装,统一处理异常
* @param onRequest 实际的 Retrofit 接口请求
* @param onSuccess 成功回调
* @param onFailure 自定义错误回调(可选,不传则用默认提示)
*/
suspend fun <T> request(
onRequest: suspend () -> ApiResponse<T>,
onSuccess: (T) -> Unit,
onFailure: (String, String) -> Unit
) {
var response: ApiResponse<T>?
try {
// 执行实际的网络请求
response = onRequest()
} catch (e: Exception) {
val apiException = getApiException(e)
onFailure("-1", apiException.errorMsg)
return
}
if (response?.isSuccess() == true) {
onSuccess(response.data as T)
} else {
onFailure(response?.code ?: "-1", response?.msg ?: "")
}
}
data class CodeMsg(
var code: String? = null,
var msg: String? = null
)
fun getApiException(e: Exception): ApiException {
// 捕获各类网络异常并转换为自定义异常
return when (e) {
is HttpException -> httpException2ApiException(e)
is UnknownHostException -> ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = "网络未连接,请检查网络"
)
is SocketTimeoutException -> ApiException(
ErrorType.TIMEOUT_ERROR,
errorMsg = "请求超时,请稍后重试"
)
is ConnectTimeoutException -> ApiException(
ErrorType.TIMEOUT_ERROR,
errorMsg = "连接超时,请检查网络"
)
is IOException -> ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = "网络异常:${e.message ?: "未知IO错误"}"
)
is ApiException -> e
else -> ApiException(
ErrorType.UNKNOWN_ERROR,
errorMsg = "未知错误:${e.message ?: "未知"}",
throwable = e
)
}
}
fun httpException2ApiException(e: HttpException): ApiException {
val body = e.response()?.errorBody()?.string()
val codeMsg: CodeMsg? = body?.toObject<CodeMsg>()
return ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = codeMsg?.msg ?: ""
)
}
@@ -0,0 +1,121 @@
package com.shuwei.dish.match.net
import com.shuwei.dish.match.base.GlobalData
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.entity.SeasoningEntity
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
import retrofit2.http.Url
interface ApiService {
// @GET("/food/stFoodInfoMatching/list")
// suspend fun getFoodList(
// @Query("dinnerType") dinnerType: String,
// @Query("canteenId") canteenId: String = BaseApp.canteenId,
// @Query("pageNo") pageNo: Int,
// @Query("pageSize") pageSize: Int
// ): ApiResponse<FoodRecordBean?>
/**
* 查询菜品详情
*/
@GET
suspend fun getFoodDetail(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/getConstituteByFoodId",
@Query("foodId") foodId: String
): ApiResponse<CookFoodEntity?>
/**
* 提交制作菜品
*/
@POST
suspend fun submitCookFood(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/saveConstitute",
@Body param: CookFoodEntity
): ApiResponse<Any?>
/**
* 搜索菜品
*/
@POST
suspend fun searchFoodList(
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryPageList",
@Body param: MutableMap<String, Any>
): ApiResponse<MutableList<FoodRecord>?>
/**
* 采样数据
*/
@POST
suspend fun getSamplingList(
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryHistoryGoodsInfoList",
@Body param: MutableMap<String, Any>
): ApiResponse<MutableList<FoodRecord>?>
/**
* 物品信息
*/
@POST
suspend fun queryGoodsList(
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryGoodsInfoList",
@Body param: MutableMap<String, Any>
): ApiResponse<MutableList<CookFoodGoodsEntity>?>
/**
* 物品信息
*/
@POST
suspend fun querySeasoningList(
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryGoodsInfoList",
@Body param: MutableMap<String, Any>
): ApiResponse<MutableList<SeasoningEntity>?>
// /**
// *获取配置信息
// */
// @GET("/equipment/stEquipment/queryByEquipmentCode")
// suspend fun getDeviceInfo(
// @Query("equipmentCode") equipmentCode: String,
// @Query("appVersion") appVersion: String = App.appVersion
// ): ApiResponse<DeviceConfigInfo>
//
// @GET
// suspend fun getAccessToken(
// @Url url: String = UrlConfig.GET_ACCESS_TOKEN,
// @Query("qrcodeId") qrcodeId: String
// ): ApiResponse<String?>
//
// @GET
// suspend fun getShelfList(
// @Url url: String = UrlConfig.GET_SHELF_LIST,
// @Query("deviceId") deviceId: String
// ): ApiResponse<ShelfResult>
//
// @GET
// suspend fun getGoodsList(
// @Url url: String = UrlConfig.GET_GOODS_LIST,
// @Query("canteenId") canteenId: String = "0",
// @Query("goodsName") goodsName: String? = null,
// @Query("pageNo") pageNo: Int = 1,
// @Query("pageSize") pageSize: Int = 50
// ): ApiResponse<MutableList<GoodsModel>?>
//
// @POST
// suspend fun saveShelfGoodsList(
// @Url url: String = UrlConfig.SAVE_SHELF_GOODS_LIST,
// @Body body: ShelfBody
// ): ApiResponse<Any?>
}
@@ -0,0 +1,68 @@
//package com.shuwei.dish.match.net
//
//import com.shuwei.dish.match.base.BaseApp
//import com.shuwei.dish.match.base.BaseReq
//import com.shuwei.dish.match.entity.FoodRecordBean
//import com.shuwei.dish.match.http.UrlConfig
//import retrofit2.http.Body
//import retrofit2.http.GET
//import retrofit2.http.POST
//import retrofit2.http.Query
//import retrofit2.http.Url
//
//interface ApiService2 {
//
// @GET("food/stFoodInfoMatching/list")
// suspend fun getDishList(
// @Query("dinnerType") dinnerType: String,
// @Query("canteenId") canteenId: String = BaseApp.canteenId,
// @Query("pageNo") pageNo: Int,
// @Query("pageSize") pageSize: Int
// ): BaseReq<FoodRecordBean?>
//
//// /**
//// * device获取token
//// */
//// @GET("/sys/getEquipmentToken")
//// suspend fun getDeviceToken(
//// @Query("qrcodeId") qrcodeId: String,
//// @Query("appVersion") appVersion: String = App.appVersion
//// ): ApiResponse<String>
////
//// /**
//// *获取配置信息
//// */
//// @GET("/equipment/stEquipment/queryByEquipmentCode")
//// suspend fun getDeviceInfo(
//// @Query("equipmentCode") equipmentCode: String,
//// @Query("appVersion") appVersion: String = App.appVersion
//// ): ApiResponse<DeviceConfigInfo>
////
//// @GET
//// suspend fun getAccessToken(
//// @Url url: String = UrlConfig.GET_ACCESS_TOKEN,
//// @Query("qrcodeId") qrcodeId: String
//// ): ApiResponse<String?>
////
//// @GET
//// suspend fun getShelfList(
//// @Url url: String = UrlConfig.GET_SHELF_LIST,
//// @Query("deviceId") deviceId: String
//// ): ApiResponse<ShelfResult>
////
//// @GET
//// suspend fun getGoodsList(
//// @Url url: String = UrlConfig.GET_GOODS_LIST,
//// @Query("canteenId") canteenId: String = "0",
//// @Query("goodsName") goodsName: String? = null,
//// @Query("pageNo") pageNo: Int = 1,
//// @Query("pageSize") pageSize: Int = 50
//// ): ApiResponse<MutableList<GoodsModel>?>
////
//// @POST
//// suspend fun saveShelfGoodsList(
//// @Url url: String = UrlConfig.SAVE_SHELF_GOODS_LIST,
//// @Body body: ShelfBody
//// ): ApiResponse<Any?>
//
//}
@@ -0,0 +1,19 @@
package com.shuwei.dish.match.net
// 1. 网络异常类型枚举
enum class ErrorType {
NETWORK_ERROR, // 网络错误(无网)
TIMEOUT_ERROR, // 超时
SERVER_ERROR, // 服务器错误(5xx
CLIENT_ERROR, // 客户端错误(4xx
PARSE_ERROR, // 数据解析错误
UNKNOWN_ERROR // 未知错误
}
// 2. 自定义网络异常类
class ApiException(
val errorType: ErrorType,
val errorCode: Int = -1,
val errorMsg: String,
val throwable: Throwable? = null
) : Exception(errorMsg, throwable)
@@ -0,0 +1,40 @@
//package com.shuwei.dish.match.net
//
//import android.annotation.SuppressLint
//import okhttp3.Interceptor
//import okhttp3.Response
//import org.apache.http.conn.ConnectTimeoutException
//import java.io.IOException
//import java.net.SocketTimeoutException
//import java.net.UnknownHostException
//
//class ExceptionInterceptor : Interceptor {
// @SuppressLint("SuspiciousIndentation")
// override fun intercept(chain: Interceptor.Chain): Response {
// val request = chain.request()
// try {
// val response = chain.proceed(request)
// // 拦截 HTTP 状态码异常(4xx/5xx
// if (!response.isSuccessful) {
// val e = ApiException(
// errorType = if (response.code >= 500) ErrorType.SERVER_ERROR else ErrorType.CLIENT_ERROR,
// errorCode = response.code,
// errorMsg = "HTTP错误:${response.code}"
// )
// throw e
// }
// return response
// } catch (e: Exception) {
// // 捕获各类网络异常并转换为自定义异常
// val apiException = when (e) {
// is UnknownHostException -> ApiException(ErrorType.NETWORK_ERROR, errorMsg = "网络未连接,请检查网络")
// is SocketTimeoutException -> ApiException(ErrorType.TIMEOUT_ERROR, errorMsg = "请求超时,请稍后重试")
// is ConnectTimeoutException -> ApiException(ErrorType.TIMEOUT_ERROR, errorMsg = "连接超时,请检查网络")
// is IOException -> ApiException(ErrorType.NETWORK_ERROR, errorMsg = "网络异常:${e.message ?: "未知IO错误"}")
// is ApiException -> e // 已转换的异常直接抛出
// else -> ApiException(ErrorType.UNKNOWN_ERROR, errorMsg = "未知错误:${e.message ?: "未知"}", throwable = e)
// }
// throw apiException
// }
// }
//}
@@ -0,0 +1,80 @@
package com.shuwei.dish.match.net
import android.annotation.SuppressLint
import android.util.Log
import com.shuwei.dish.match.http.UrlConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
import java.security.SecureRandom
import java.security.cert.X509Certificate
import kotlin.apply
import kotlin.jvm.java
val apiService: ApiService = Retrofit.Builder()
.baseUrl(UrlConfig.BASE_URL)
// .baseUrl(UrlConfig.DEVICE_BASE_URL)
.client(HttpManager.instance.client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
//val apiService2: ApiService2 = Retrofit.Builder()
// .baseUrl(UrlConfig.BASE_URL)
//// .baseUrl(UrlConfig.DEVICE_BASE_URL)
// .client(HttpManager.instance.client)
// .addConverterFactory(GsonConverterFactory.create())
// .build()
// .create(ApiService2::class.java)
class HttpManager private constructor() {
val client: OkHttpClient by lazy {
OkHttpClient.Builder()
.apply {
connectTimeout(15, TimeUnit.SECONDS)
readTimeout(30, TimeUnit.SECONDS)
writeTimeout(15, TimeUnit.SECONDS)
sslSocketFactory(createSSLSocketFactory(), TrustAllCerts())
hostnameVerifier { _, _ -> true }
addNetworkInterceptor(HttpLoggingInterceptor(logger = {
Log.d("HttpManager", "okhttp logger ==>${it}")
}).also {
it.level = HttpLoggingInterceptor.Level.BODY
})
addInterceptor(RequestInterceptor())
// addInterceptor(ExceptionInterceptor())
}
.build()
}
companion object {
val instance by lazy { HttpManager() }
}
// 信任所有证书的TrustManager实现
@SuppressLint("CustomX509TrustManager")
class TrustAllCerts : X509TrustManager {
@SuppressLint("TrustAllX509TrustManager")
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
}
@SuppressLint("TrustAllX509TrustManager")
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
// 创建信任所有证书的SSLSocketFactory
fun createSSLSocketFactory(): SSLSocketFactory {
val sslContext = SSLContext.getInstance("TLS").apply {
init(null, arrayOf(TrustAllCerts()), SecureRandom())
}
return sslContext.socketFactory
}
}
@@ -0,0 +1,141 @@
package com.shuwei.dish.match.net
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.entity.SeasoningEntity
import kotlinx.coroutines.launch
class NetViewModel : ViewModel() {
// fun getFoodList(
// dinnerType: String,
// pageNo: Int,
// pageSize: Int,
// onSuccess: (FoodRecordBean?) -> Unit,
// onFailure: (String, String) -> Unit
// ) {
// viewModelScope.launch {
// apiRequest(
// onRequest = {
// apiService2.getDishList(
// dinnerType = dinnerType,
// pageNo = pageNo,
// pageSize = pageSize
// )
// },
// onSuccess = {
// if (it.code == 200) {
// onSuccess(it.data)
// return@apiRequest
// }
// onFailure("${it.code}", it.msg ?: "")
// },
// onFailure = {
// onFailure("-1", it.errorMsg)
// }
// )
// }
// }
fun submitCookFood(
entity: CookFoodEntity,
onSuccess: (Any?) -> Unit,
onFailure: (String, String) -> Unit
) {
viewModelScope.launch {
request(
onRequest = {
apiService.submitCookFood(param = entity)
},
onSuccess = onSuccess,
onFailure = onFailure
)
}
}
fun getFoodDetail(
foodId: String,
onSuccess: (CookFoodEntity?) -> Unit,
onFailure: (String, String) -> Unit
) {
viewModelScope.launch {
request(
onRequest = {
apiService.getFoodDetail(foodId = foodId)
},
onSuccess = onSuccess,
onFailure = onFailure
)
}
}
fun searchFoodList(
param: MutableMap<String, Any>,
onSuccess: (MutableList<FoodRecord>?) -> Unit,
onFailure: (String, String) -> Unit
) {
viewModelScope.launch {
request(
onRequest = {
apiService.searchFoodList(param = param)
},
onSuccess = onSuccess,
onFailure = onFailure
)
}
}
fun getSamplingList(
param: MutableMap<String, Any>,
onSuccess: (MutableList<FoodRecord>?) -> Unit,
onFailure: (String, String) -> Unit
) {
viewModelScope.launch {
request(
onRequest = {
apiService.getSamplingList(param = param)
},
onSuccess = onSuccess,
onFailure = onFailure
)
}
}
fun queryGoodsList(
param: MutableMap<String, Any>,
onSuccess: (MutableList<CookFoodGoodsEntity>?) -> Unit,
onFailure: (String, String) -> Unit
) {
viewModelScope.launch {
request(
onRequest = {
apiService.queryGoodsList(param = param)
},
onSuccess = onSuccess,
onFailure = onFailure
)
}
}
fun querySeasoningList(
param: MutableMap<String, Any>,
onSuccess: (MutableList<SeasoningEntity>?) -> Unit,
onFailure: (String, String) -> Unit
) {
viewModelScope.launch {
request(
onRequest = {
apiService.querySeasoningList(param = param)
},
onSuccess = onSuccess,
onFailure = onFailure
)
}
}
}
@@ -0,0 +1,22 @@
package com.shuwei.dish.match.net
import com.shuwei.dish.match.base.GlobalData
import okhttp3.Interceptor
import okhttp3.Response
/**
* 请求拦截器
*/
class RequestInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val requestBuilder = originalRequest.newBuilder()
.header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiJiZTE1NDgzMS0zNDY2LTNiYTItYTJlYS01NzY1MmM5MTlmZWQiLCJ0eXBlIjoiNCIsInVzZXJJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDEifQ.sN40cOC-O5WQFrF4IDUs8fFlkNdUKLbJt_rHyTsgYYM")
.header("X-DEVICE-CODE", GlobalData.deviceId)
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
val newRequest = requestBuilder.build()
return chain.proceed(newRequest)
}
}
@@ -0,0 +1,9 @@
package com.shuwei.dish.match.net
data class ApiResponse<T>(
val code: String,
val msg: String? = "",
val data: T? = null
) {
fun isSuccess() = code == "00000"
}