RetrofitClient.kt 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package com.example.pda.network
  2. import retrofit2.Retrofit
  3. import retrofit2.converter.gson.GsonConverterFactory
  4. import com.example.pda.model.AppPrefs
  5. // RetrofitClient 对象用于创建和管理 Retrofit 实例
  6. // 添加重置方法
  7. object RetrofitClient {
  8. private var retrofitInstance: Retrofit? = null
  9. private var apiService: ApiService? = null
  10. fun reset() {
  11. retrofitInstance = null
  12. apiService = null
  13. }
  14. val instance: ApiService
  15. get() {
  16. if (apiService == null) {
  17. retrofitInstance = Retrofit.Builder()
  18. .baseUrl(formatBaseUrl(AppPrefs.base_url))
  19. .client(HttpClient.instance)
  20. .addConverterFactory(GsonConverterFactory.create())
  21. .build()
  22. apiService = retrofitInstance!!.create(ApiService::class.java)
  23. }
  24. return apiService!!
  25. }
  26. private fun formatBaseUrl(url: String): String {
  27. var formatted = url
  28. if (!formatted.startsWith("http")) formatted = "http://$formatted"
  29. if (!formatted.endsWith("/")) formatted += "/"
  30. return formatted
  31. }
  32. }