๐ฑ dreaming DiNO
[Kotlin] Retrofit - Logging Interceptor ์ ํ์์ฑ ๋ณธ๋ฌธ
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)
์ด๋ฐ์์ผ๋ก ๋ก๊ทธ ๋ด์ฉ์ ๋ณด์ฌ์ค๋ค!
'Android' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Kotlin] ๋๋ค์ / SAM๋ณํ /ํ์ฅํจ์ (0) | 2021.12.09 |
---|---|
[Kotlin] APIํธ์ถํด์ ๋ฐ์ JSON Dataํ์ฑํ๊ธฐ (0) | 2021.12.08 |
[Kotlin] Retrofit (๋ ํธ๋กํ) ์ด๋? (0) | 2021.11.24 |
[Kotlin] ๊ธฐ๋ณธ๋ฌธ๋ฒ-2 (0) | 2021.11.24 |
[Kotlin] ๊ธฐ๋ณธ๋ฌธ๋ฒ-1 (0) | 2021.11.24 |