1.안드로이드 retrofit 사용 따라하기

1.안드로이드 retrofit 따라하기

1.build.gradle에 의존성추가

implementation 'com.squareup.retrofit2:retrofit:2.8.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.4'
implementation "com.squareup.okhttp3:logging-interceptor:4.9.3"

 

2.매니패스트에 설정추가

<uses-permission android:name="android.permission.INTERNET" />

 

3.설정 상수 

package com.example.myapplication

object Constant {
    const val TAG:String = "로그"
}

enum class RESPONSE_STATE{
    OK,
    FAIL
}

//
object API{
    const val BASE_URL:String = "https://www.ooo.kr/"
    const val TEST_API:String = "users/listTest"
}

 

 

4.string 확장 함수

 

package com.example.myapplication

fun String?.isJsonObject():Boolean{
    if(this?.startsWith("{") == true && this.endsWith("}")){
      return true
    }else{
        return false
    }
}

fun String?.isJsonArray():Boolean{
    if(this?.startsWith("[") == true && this.endsWith("]")){
        return true
    }else{
        return false
    }
}

 

5.래트로핏 인터페이스 작성

package com.example.myapplication

import com.google.gson.JsonElement
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface IRetrofit {
    @GET(API.TEST_API)
    fun searchTest():Call<JsonElement>
}

 

6.레트로핏 클라이언트 설정

package com.example.myapplication

import android.util.Log
import com.google.gson.JsonObject
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
import java.util.concurrent.TimeUnit

//object : 싱글턴
object RetrofitClient{

    private var retrofitClient:Retrofit? = null

    //레트로핏 믈라이언트 가져오기
    fun getClient(baseUrl:String):Retrofit?{
    //okhttp 인스턴스 생성
        var client = OkHttpClient.Builder()

        //로그를 찍기위해 로깅 인터셉터 추가
        val logInterceptor = HttpLoggingInterceptor(object :HttpLoggingInterceptor.Logger{
            override fun log(message: String) {
                Log.d(Constant.TAG,"Retrofit-Client calld - msg: ${message}")

                when{
                    message.isJsonObject() ->
                        Log.d(Constant.TAG , JSONObject(message).toString(4))
                    message.isJsonArray() ->
                        Log.d(Constant.TAG , JSONObject(message).toString(4))
                    else -> {
                        try{
                            Log.d(Constant.TAG , JSONObject(message).toString(4))
                        }catch (e:Exception){
                            Log.d(Constant.TAG , message)
                        }
                    }
                }
            }
        })

        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

        //위에서 설정한 인터셉터를 okhttp 클라이언트에 추가한다.
        client.addInterceptor(logInterceptor)


        var baseParamInterceptor : Interceptor = (object  : Interceptor{
            override fun intercept(chain: Interceptor.Chain): Response {
                val originalRequest : Request = chain.request()

                val newReq = originalRequest.newBuilder()
                    .addHeader("authorization" , "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6IuyYgeq3oCIsImlkIjoiZTQzYjVjdnBlYkBwcml2YXRlcmVsYXkuYXBwbGVpZC5jb20iLCJhdXRoIjoiVVNFUiIsImlhdCI6MTY0MzYxNTQ1MywiZXhwIjoxNjQ4NDE1NDUzfQ.dLwuFTJ8wyjzfcmPS_8KkT84r2OzG9EA3bg-mWP8cqQ")
                    .build()
                return  chain.proceed(newReq)
            }
        })

        //위에서 설정한 헤더 인터셉터를 okhttp에 추가한다.
        client.addInterceptor(baseParamInterceptor)

        //커넥션 타임아웃
        client.connectTimeout(10,TimeUnit.SECONDS)
        client.readTimeout(10, TimeUnit.SECONDS)
        client.writeTimeout(10,TimeUnit.SECONDS)
        client.retryOnConnectionFailure(true)


        if (retrofitClient == null){

            //레트로핏 빌더를 통해 인스턴스 생성
            retrofitClient = Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())

                //위에서 설정한 클라이언트로 레트로핏 클라이언트를 설정한다.
                .client(client.build())
                .build()
        }
        return retrofitClient
    }


}

 

7.레트로핏 매니저 설정

 

package com.example.myapplication

import android.util.Log
import com.google.gson.JsonElement
import retrofit2.Call
import retrofit2.Response
import retrofit2.create

class RetrofitManager {

    companion object{
        val instance = RetrofitManager()
    }

    //레트로핏 인터페이스 가져오기
    private val iRetrofit:IRetrofit?= RetrofitClient.getClient(API.BASE_URL)?.create(IRetrofit::class.java)


    fun searchTest(completion:(RESPONSE_STATE, String)->Unit){
        val call :Call<JsonElement> = iRetrofit?.searchTest().let {
            it
        }?: return

        call.enqueue(object : retrofit2.Callback<JsonElement>{
            //응답성공시
            override fun onResponse(call: Call<JsonElement>, response: Response<JsonElement>) {
                Log.d(Constant.TAG, "success / res : ${response.body()}")
                completion(RESPONSE_STATE.OK, response.body().toString())
            }

            //응답실패시
            override fun onFailure(call: Call<JsonElement>, t: Throwable) {
                Log.d(Constant.TAG, "fail")
                completion(RESPONSE_STATE.FAIL, t.toString())
            }
        })
}}

 

호출하기

 

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {

    // 엑티비티가 생성되었을때
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //레이아웃을 설정
        setContentView(R.layout.activity_main)

        RetrofitManager.instance.searchTest {
            resState , response ->
            when(resState){
                RESPONSE_STATE.OK -> {
                    Log.d(Constant.TAG , "api 호출 성공 : ${response}")
                }
                RESPONSE_STATE.FAIL ->{
                    Log.d(Constant.TAG , "api 호출 실패 : ${response}")
                }
            }
        }
    }
}