• 使用建造者模式实例化Retrofit

      1. private fun retrofit(): Retrofit = Retrofit.Builder()
      2. // 后端接口地址
      3. .baseUrl("http://192.168.0.100:00002")
      4. // 将值转化为JSON格式
      5. .addConverterFactory(GsonConverterFactory.create())
      6. .build()
      7. // 实例化接口
      8. val webservice:Webservice = retrofit().create(Webservice::class.java)
    • 定义请求接口:

      interface Webservice {
        /**
         * 请求列表
         * @param peddle
         * @return liveList
         */
        @POST("/live/find/all")
        fun getLiveList(@Body peddle: Peddle): Call<LiveList>
      }
      
    • 在类中使用

      /*
      * Copyright (c) 2020 www.ai-wsd.com Inc. All rights reserved
      */
      class UserRepository {
        private val webservice: Webservice = ApiService.webservice
        fun getLiveList():LiveData<LiveList>{
            val data = MutableLiveData<LiveList>()
            // peddle为实体类
            val peddle = Peddle(1,3)
            webservice.getLiveList(peddle).enqueue(object : Callback<LiveList> {
                override fun onResponse(call: Call<LiveList>, response: Response<LiveList>) {
                    data.value = response.body()
                }
      
                override fun onFailure(call: Call<LiveList>, t: Throwable) {
                    Log.e(TAG, "onFailure: $t")
                }
      
            })
            return data
        }
      
        companion object{
            const val TAG = "UserRepository"
        }
      }
      
    • 依赖添加

      implementation 'com.squareup.retrofit2:retrofit:2.9.0'
      implementation 'com.squareup.retrofit2:converter-gson:2.9.0'