티스토리 뷰

android

retrofit

노명규 2022. 9. 21. 14:10
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitBuilder {
    private fun getRetrofit():Retrofit {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val client = OkHttpClient.Builder().
                        addInterceptor(httpLoggingInterceptor).build()

        val retrofit = Retrofit.Builder().
                        baseUrl("https://api.com/").
                        addConverterFactory(GsonConverterFactory.create()).
                        client(client).build()

        return retrofit;
    }

    fun getApiService() :RetrofitApi {
        return getRetrofit().create(RetrofitApi::class.java)
    }
}
interface RetrofitApi {
    // &user_id={id}&user_name={name}
    @GET("../path")
    fun get(
        @Query("user_id") id: String,
        @Query("user_name") name: String,
        ) :Call<vo 객체>
}

주석처럼 &key=value는 @Query를 사용하면 알아서 url에 붙여줌 

getApiService().get("아이디","이름").enqueue(object : Callback<vo객체> {
    override fun onResponse(call: Call<vo객체>, response: Response<vo객체>) {
        if(response.isSuccessful){
            val result: vo객체? = response.body()
        }
    }
    override fun onFailure(call: Call<Model_CheckCoupon>, t: Throwable) {
        
    }
})

 

 

 

HttpLoggingInterceptor

이건 로그를 위한...  okhttp로 태그걸면 통신 관련 로그 다 나옴,

 

 

 

 

body 사용법

@POST("...path")
fun setBody(@Body v : testBody) : Call<vo객체>
data class testBody (
    @SerializedName("id") val id: String,
    @SerializedName("pw") val pw: String
)

SerializedName 넣어야 함.. 이러면 자동으로 json 파싱해줌

'android' 카테고리의 다른 글

retrofit으로, rx and coroutine  (0) 2023.02.03
android mvvm 예제  (0) 2023.01.30
by viewmodels() 쓰는법,  (0) 2022.08.18
android Frame Animation, Animation Drawable 사용 방법  (0) 2020.04.27
AnimationDrawable memory 문제.  (0) 2020.04.27