This commit is contained in:
2026-04-28 11:01:10 +08:00
parent 1b62e4d264
commit 8a5f599266
15 changed files with 419 additions and 32 deletions

View File

@@ -0,0 +1,14 @@
package com.example.defenseapplication.utils
import com.google.gson.Gson
import okhttp3.OkHttpClient
import retrofit2.http.GET
interface ApiService {
// 获取登录注册验证码
@GET("/resource/sms/code")
suspend fun getCode(): String
}

View File

@@ -0,0 +1,8 @@
package com.example.defenseapplication.utils
data class Post(
val userId: Int,
val id: Int,
val title: String,
val body: String
)

View File

@@ -0,0 +1,43 @@
package com.example.defenseapplication.utils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
//网络工具类
object HttpUtils {
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.writeTimeout(3, TimeUnit.MINUTES)
.readTimeout(3, TimeUnit.MINUTES)
.addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val s = UserinfoUtil.getUserInfo()
val aa = chain.request().newBuilder()
.addHeader("token", s?.token ?: "")
.addHeader("userId", "${s?.userId ?: 0}")
.build()
return chain.proceed(aa)
}
})
.build()
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.baseUrl("https://stem-boozy-margarine.ngrok-free.dev")
.build()
val api = retrofit.create(ApiService::class.java)
}

View File

@@ -0,0 +1,27 @@
package com.example.defenseapplication.utils
import bean.LoginBean
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
//存储登录的token和userid
object UserinfoUtil {
private const val KEY_USER = "NAME_USER"
private val gson = Gson()
fun saveUserInfo(userinfo: LoginBean?) {
userinfo ?: return
val json = gson.toJson(userinfo)
SPUtils.getInstance().put(KEY_USER, json)
}
fun getUserInfo(): LoginBean? {
val string = SPUtils.getInstance().getString(KEY_USER)
if (string.isNullOrEmpty()) {
return null
}
return gson.fromJson(string, LoginBean::class.java)
}
}