代码提交
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package com.shuwei.dish.match.http
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.util.Log
|
||||
import okhttp3.Call
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
import javax.net.ssl.*
|
||||
import java.security.SecureRandom
|
||||
import java.security.cert.X509Certificate
|
||||
|
||||
class HttpClient private constructor() {
|
||||
private 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 }
|
||||
//if (BuildConfig.Debug) {
|
||||
addInterceptor(LoggingInterceptor())
|
||||
// }
|
||||
}
|
||||
.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
val instance by lazy { HttpClient() }
|
||||
}
|
||||
|
||||
fun newCall(request: Request): Call = client.newCall(request)
|
||||
|
||||
inner class LoggingInterceptor : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request()
|
||||
// 打印请求日志
|
||||
Log.d("OkHttp", "--> ${request.method} ${request.url}")
|
||||
|
||||
val response = chain.proceed(request)
|
||||
// 打印响应日志
|
||||
Log.d("OkHttp", "<-- ${response.code} ${response.request.url}")
|
||||
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
// 信任所有证书的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,166 @@
|
||||
package com.shuwei.dish.match.http
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.BaseReq
|
||||
import com.shuwei.dish.match.http.HttpUtil.runMainThread
|
||||
import com.shuwei.dish.match.utils.ext.put
|
||||
import com.shuwei.dish.match.utils.ext.toType
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
|
||||
|
||||
object HttpUtil {
|
||||
|
||||
fun runMainThread(action: () -> Unit) {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
// GET请求(HTTPS)
|
||||
fun get(
|
||||
url: String,
|
||||
doSuccess: (data: Any) -> Unit,
|
||||
doFailure: (code: Int?, msg: String?) -> Unit
|
||||
) {
|
||||
val token = getToken()
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.apply {
|
||||
if (token.isNotBlank()) {
|
||||
addHeader("X-Access-Token", token)
|
||||
}
|
||||
}
|
||||
.get()
|
||||
.build()
|
||||
HttpClient.instance.newCall(request).enqueue(CallbackImpl(doSuccess, doFailure))
|
||||
}
|
||||
|
||||
fun get(
|
||||
isHttps: Boolean = false,
|
||||
host: String = "vip.shuziweidao.com",
|
||||
pathSegmentList: List<String>,
|
||||
queryParams: Map<String, String>,
|
||||
doSuccess: (data: Any) -> Unit,
|
||||
doFailure: (code: Int?, msg: String?) -> Unit
|
||||
) {
|
||||
val token = getToken()
|
||||
val url = HttpUrl.Builder()
|
||||
.scheme(if (isHttps) "https" else "http")
|
||||
.host(host)
|
||||
.apply {
|
||||
pathSegmentList.forEach { addPathSegment(it) }
|
||||
queryParams.forEach { (key, value) -> addQueryParameter(key, value) }
|
||||
}
|
||||
.build()
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.apply {
|
||||
if (token.isNotBlank()) {
|
||||
addHeader("Authorization", token)
|
||||
}
|
||||
}
|
||||
.get()
|
||||
.build()
|
||||
HttpClient.instance.newCall(request).enqueue(CallbackImpl(doSuccess, doFailure))
|
||||
}
|
||||
|
||||
// POST表单(HTTPS)
|
||||
// fun postForm(url: String, params: Map<String, String>, callback: Callback) {
|
||||
// val formBody = FormBody.Builder().apply {
|
||||
// params.forEach { (k, v) -> add(k, v) }
|
||||
// }.build()
|
||||
//
|
||||
// Request.Builder()
|
||||
// .url(url)
|
||||
// .post(formBody)
|
||||
// .build().let { HttpClient.instance.newCall(it).enqueue(callback) }
|
||||
// }
|
||||
|
||||
// POST JSON(HTTPS)
|
||||
fun postJson(
|
||||
url: String,
|
||||
json: String,
|
||||
doSuccess: (data: Any) -> Unit,
|
||||
doFailure: (code: Int?, msg: String?) -> Unit
|
||||
) {
|
||||
val body = json
|
||||
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
|
||||
val token = getToken()
|
||||
Request.Builder()
|
||||
.url(url)
|
||||
.apply {
|
||||
if (token.isNotBlank()) {
|
||||
addHeader("X-Access-Token", token)
|
||||
}
|
||||
}
|
||||
.post(body)
|
||||
.build()
|
||||
.let { HttpClient.instance.newCall(it).enqueue(CallbackImpl(doSuccess, doFailure)) }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CallbackImpl(
|
||||
private val doSuccess: (data: Any) -> Unit,
|
||||
private val doFailure: (code: Int?, msg: String?) -> Unit
|
||||
) :
|
||||
Callback {
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
runMainThread {
|
||||
e.printStackTrace()
|
||||
doFailure(-1, "服务异常,${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
val respData = response.body?.string()
|
||||
runMainThread {
|
||||
Log.d("HttpUtil", respData ?: "")
|
||||
runCatching {
|
||||
val typeToken = object : TypeToken<BaseReq<Any>>() {}
|
||||
val baseReq = respData?.toType<BaseReq<Any>>(typeToken = typeToken)
|
||||
if (baseReq == null) {
|
||||
doFailure(-1, "查询数据失败")
|
||||
return@runCatching
|
||||
}
|
||||
if (baseReq.code != 200) {
|
||||
doFailure(baseReq.code, baseReq.message)
|
||||
if (baseReq.code == 500 || baseReq.code == 401) {
|
||||
getAppToken()
|
||||
}
|
||||
return@runCatching
|
||||
}
|
||||
doSuccess(baseReq.result ?: "")
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
doFailure(-1, "解析异常")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getToken() = BaseApp.instance?.token ?:""
|
||||
//BaseApp.getSharedPref()?.getString("token", "") ?: ""
|
||||
|
||||
private fun getAppToken() {
|
||||
val url = "${UrlConfig.GET_TOKEN}?qrcodeId=${BaseApp.instance?.androidId}"
|
||||
// Log.d(TAG, "getToken: url = $url")
|
||||
HttpUtil.get(url = url, doSuccess = {
|
||||
BaseApp.getSharedPref()?.put("token" to it)
|
||||
BaseApp.instance?.token = it.toString()
|
||||
}) { code, msg ->
|
||||
//toast(msg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.shuwei.dish.match.http
|
||||
|
||||
object UrlConfig {
|
||||
|
||||
// const val BASE_URL = "http://vip.shuziweidao.com/shuwei-zhct"
|
||||
// const val DISH_DETAIL = "$BASE_URL/scales/goodsUseList?foodId={foodId}&foodWeight={foodWeight}"
|
||||
// const val DISH_LIST = "$BASE_URL/scales/getRestInfoFoods?eaId=99&type=0&foodName"
|
||||
|
||||
const val BASE_URL = "http://192.168.1.207:9102"
|
||||
// const val DISH_LIST = "$BASE_URL/scales/getRestInfoFoods?eaId=99&type=0&foodName"
|
||||
|
||||
const val DISH_DETAIL = "$BASE_URL/food/stFoodInfoMatching/queryById"
|
||||
|
||||
// "$BASE_URL/scales/generateToken?deviceId=1111111111111111111111111111"
|
||||
|
||||
const val GET_TOKEN = "$BASE_URL/restaurant/equipment/stEquipment/getEquipmentToken"
|
||||
const val SUBMIT_DISH = "$BASE_URL/food/stFoodInfoMatching/saveoredit"
|
||||
|
||||
const val QUERY_GOODS_LIST = "$BASE_URL/food/stFoodInfoMatching/queryGoodsInfoList"
|
||||
const val QUERY_FOOD_LIST = "$BASE_URL/food/stFoodInfoMatching/list"
|
||||
const val SAMPLING_LIST = "$BASE_URL/food/stFoodInfoMatching/queryHistorical/goodsInfoList"
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user