当前位置:   article > 正文

Kotlin Retrofit 网络请求

Kotlin Retrofit 网络请求

一、添加依赖:

  1. //Retrofit 网络请求
  2. implementation("com.squareup.retrofit2:retrofit:2.3.0")
  3. implementation("com.squareup.retrofit2:converter-gson:2.3.0")//json转换

二、创建单例类:

  1. package com.example.buju.http
  2. import okhttp3.OkHttpClient
  3. import retrofit2.Retrofit
  4. import retrofit2.converter.gson.GsonConverterFactory
  5. import java.util.concurrent.TimeUnit
  6. /**
  7. * retrofit网络请求
  8. * */
  9. object HiRetrofit {
  10. val client = OkHttpClient.Builder()// builder构造者设计模式
  11. .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
  12. .readTimeout(10, TimeUnit.SECONDS)// 读取超时
  13. .writeTimeout(10, TimeUnit.SECONDS)// 写超时
  14. .addInterceptor(LoggingInterceptor())// 自定义拦截器
  15. .build()
  16. private var retrofit:Retrofit = Retrofit.Builder() // Builder构造者设计模式
  17. .client(client)// 借助okhttp3创建的client
  18. .baseUrl("baseUrl")// 网络请求前面的公共地址
  19. .addConverterFactory(GsonConverterFactory.create())// 数据转换适配器
  20. .build()
  21. fun <T> create(clazz: Class<T>):T{
  22. return retrofit.create(clazz)
  23. }
  24. }

 三、创建网络请求Api:

  1. package com.example.buju.http
  2. import retrofit2.Call
  3. import retrofit2.http.GET
  4. import retrofit2.http.Query
  5. /**
  6. * retrofit网络请求定义Api
  7. * */
  8. interface ApiService {
  9. // 根据用户id查询信息
  10. @GET(value = "user/query")
  11. fun queryUser(@Query(value="userId",encoded = true) userId:String):Call<HashMap<String,String>>
  12. }

使用:

  1. val apiService:ApiService = HiRetrofit.create(ApiService::class.java)
  2. apiService.queryUser("0001").enqueue(object:Callback<HashMap<String,String>>{
  3. override fun onResponse(
  4. call: Call<HashMap<String, String>>,
  5. response: Response<HashMap<String, String>>
  6. ) {
  7. Log.e("Retrofit",response.body()?.toString() ?:"不知道原因")
  8. }
  9. override fun onFailure(call: Call<HashMap<String, String>>, t: Throwable) {
  10. Log.e("Retrofit",t.message?:"不知道原因")
  11. }
  12. })

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/230966
推荐阅读
相关标签
  

闽ICP备14008679号