Notice
Recent Posts
Recent Comments
Link
ยซ   2025/05   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐ŸŒฑ dreaming DiNO

[Kotlin] Retrofit - Logging Interceptor ์˜ ํ•„์š”์„ฑ ๋ณธ๋ฌธ

Android

[Kotlin] Retrofit - Logging Interceptor ์˜ ํ•„์š”์„ฑ

MK_____ 2021. 12. 7. 22:38

Logging Interceptor ์ ์šฉ ์ „

RetrofitManager.searchPhotos(keyword, completion = {
    responseState, response ->
    when(responseState) {
        RESPONSE_STATE.OKAY -> {
            Toast.makeText(this, "ํ˜ธ์ถœ์„ฑ๊ณต!", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "response OK! / reponseBody : $response")

        }
        RESPONSE_STATE.FAIL -> {
            Toast.makeText(this, "ํ˜ธ์ถœ์‹คํŒจใ…กใ…ก", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "response No! / t : $response")
        }
    }
})

Unsplash API - GET ๋ฐฉ์‹ ํ˜ธ์ถœ์„ ํ–ˆ๋Š”๋ฐ, ์ฟผ๋ฆฌ์— client_id๊ฐ€ ์—†์ด ํ˜ธ์ถœํ•œ ๋ถ€๋ถ„์ด๋‹ค.

API๊ฐ€ ์ œ๋Œ€๋กœ ์ฐ”๋ฆฌ๊ธด ํ–ˆ์ง€๋งŒ, ๋ฐ›์€ response๋ฅผ ๋กœ๊ทธ์— ์ฐ์–ด๋ณด๋ฉด null ์ด ๋‚˜์˜จ๋‹ค.

์™œ null์ธ์ง€, ์ด ๋‚ด์šฉ์„ ๋ณด์—ฌ์ฃผ๋„๋ก ์•Œ๊ธฐ ์œ„ํ•ด ๋กœ๊น… ์ธํ„ฐ์…‰ํ„ฐ๊ฐ€ ํ•„์š”ํ•˜๋‹ค! 

 

Logging Interceptor ์ ์šฉ ํ›„

fun getClient(baseUrl: String) : Retrofit?{
    // ๋กœ๊ทธ ์ฐ๊ธฐ์œ„ํ•ด ๋กœ๊น…์ธํ„ฐ์…‰ํ„ฐ ํ•„์š”
    // ํด๋ผ์ด์–ธํŠธ ๋ฉ”๋ชจ๋ฆฌ์— ์˜ฌ๋ฆผ
    val client = OkHttpClient.Builder()
    val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger{
        override fun log(message: String) {
            Log.d(TAG, "RetrofitClient - log() ํ˜ธ์ถœ / message : $message")
            //extension ์‚ฌ์šฉ
            when {
                message.isJsonObject() ->
                    Log.d(TAG, "RetrofitClient - log() JsonObject : true \n" +
                            JSONObject(message).toString(4)) //๋“ค์—ฌ์“ฐ๊ธฐ
                message.isJsonArray() ->
                    Log.d(TAG, "RetrofitClient - log() JsonArray : true \n" +
                            JSONArray(message).toString(4)) //๋“ค์—ฌ์“ฐ๊ธฐ
                else ->
                    try {
                        Log.d(TAG, "RetrofitClient - Json์ด ์•„๋‹ˆ์•ผ / messsage: $message")
                    }catch (e: Exception){
                        Log.d(TAG, "RetrofitClient - Json์ด ์•„๋‹ˆ์•ผ / message: $message")
                    }
            }
        }
    })

    //๋กœ๊น… ์ธํ„ฐ์…‰ํ„ฐ ๋ ˆ๋ฒจ ์„ค์ •
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
    //์ด๋ ‡๊ฒŒ ์„ค์ •์„ธํŒ…ํ•œ ๋กœ๊น… ์ธํ„ฐ์…‰ํ„ฐ๋ฅผ ์—ฐ๊ฒฐ
    client.addInterceptor(loggingInterceptor)

์ด๋Ÿฐ์‹์œผ๋กœ ๋กœ๊ทธ ๋‚ด์šฉ์„ ๋ณด์—ฌ์ค€๋‹ค!