El proyecto de Android integra Retrofit para solicitudes de red
1. Agregar dependencias del proyecto
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.7.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
2. Cree una clase de procesamiento de modificación básica
import android.util.Log
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class RetrofitUtils private constructor() {
fun <T> getApiService(cl: Class<T>): T {
val retrofit = getRetrofit()
return retrofit.create(cl)
}
companion object {
//TODO 网络请求的 BASE_URL
private const val BASE_URL = "这里是你的网络请求的baseUrl"
private var retrofitUtils: RetrofitUtils? = null
val instance: RetrofitUtils
get() {
if (retrofitUtils == null) {
synchronized(RetrofitUtils::class.java) {
if (retrofitUtils == null) {
retrofitUtils = RetrofitUtils()
}
}
}
return retrofitUtils!!
}
private var retrofit: Retrofit? = null
@Synchronized
private fun getRetrofit(): Retrofit {
val interceptor = HttpLoggingInterceptor { message -> Log.d("xxx", message) }
interceptor.level = HttpLoggingInterceptor.Level.BODY
val ok = OkHttpClient.Builder()
.addInterceptor(interceptor).connectTimeout(5000, TimeUnit.MILLISECONDS)
if (retrofit == null) {
retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
}
return retrofit!!
}
}
}
3. Cree una interfaz que solicite métodos de interfaz específicos
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.POST
/**
*
* @ClassName: InterfaceRequestApi
* @Description:
* @Author: leeeeef
* @CreateDate: 2019/12/24 17:11
*/
interface InterfaceRequestApi {
//get请求
@GET("这里是接口具体的url")
fun getIndexTitles(): Call<请求返回的结果bean对象>
//post请求,form表单提交请求参数(id, page)
@FormUrlEncoded
@POST("这里是接口具体的url")
fun getIndexHotData(@Field("id") id: Int, @Field("page") page: Int): Call<请求返回的结果bean对象>
}
4. Utilice una rutina para abrir la solicitud de red
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.myapplication.net.IndexTitle
import com.example.myapplication.net.InterfaceRequestApi
import com.example.myapplication.net.RetrofitUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.CoroutineContext
class MainActivity : AppCompatActivity(),CoroutineScope {
private lateinit var mJob:Job
override val coroutineContext: CoroutineContext
get() = mJob + Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mJob=Job()
}
override fun onDestroy() {
super.onDestroy()
mJob.cancel()
}
//网络请求
private fun request() {
launch {
val result = RetrofitUtils.instance.getApiService(InterfaceRequestApi::class.java)
.getIndexTitles().enqueue(object : Callback<IndexTitle> {
override fun onFailure(call: Call<IndexTitle>, t: Throwable) {
//请求失败处理
}
override fun onResponse(
call: Call<IndexTitle>,
response: Response<IndexTitle>
) {
//请求成功处理
}
})
}
}
}