ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] Retrofit
    카테고리 없음 2024. 5. 14. 10:02

    Retrofit이란?

    서버와 클라이언트간에 HTTP 통신을 쉽게 도와주는 라이브러리입니다.


    사용법

     

    1. gradle 설정

    개발에 필요한 gson, retrofit2, okhttp3를 적어줍니다.

    implementation("com.google.code.gson:gson:2.10.1")
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")
    implementation("com.squareup.okhttp3:okhttp:4.11.0")
    implementation("com.squareup.okhttp3:logging-interceptor:4.10.0")

     

    2. API 받아오기

    오늘은 Retrofit을 사용하여 구글의 YouTube Data API v3를 이용하여 영상 데이터를 가져와볼겁니다.

    API 발급은 아래 사이트에서 하시면 됩니다.

    구글 유튜브 API 발급 사이트 바로가기

     

    3. Json 데이터 파싱하기

    구글에서 JSON 구조는 아래처럼 되어있다고 합니다.

    원래는 이걸 다 일일히 적어주셔야 하지만 여러분은 제가 적어놓은걸로 하시면 됩니다.


    여기서 @SerializedName은 어노테이션으로 필드 변수 이름과
    JSON에 적힌 key와 다르게 하고 싶을 때 사용하시면 됩니다.

    (만약 필드 변수 이름과 JSON의 key가 같다면 적어주지 않아도 됩니다.)

    data class SearchResponse(
        @SerializedName("kind")
        val kind: String,
        @SerializedName("etag")
        val eTag: String,
        @SerializedName("nextPageToken")
        val nextPageToken: String,
        @SerializedName("regionCode")
        val regionCode: String,
        @SerializedName("pageInfo")
        val pageInfo: PageInfoResponse,
        @SerializedName("items")
        val items: List<ItemResponse>
    )
    
    data class PageInfoResponse(
        @SerializedName("totalResults")
        val totalResults: Int,
        @SerializedName("resultsPerPage")
        val resultsPerPage: Int
    )
    
    data class ItemResponse(
        @SerializedName("kind")
        val kind: String,
        @SerializedName("etag")
        val eTag: String,
        @SerializedName("id")
        val id: IdResponse,
        @SerializedName("snippet")
        val snippet: SnippetResponse
    )
    
    data class IdResponse(
        @SerializedName("kind")
        val kind: String,
        @SerializedName("videoId")
        val videoId: String
    )
    
    data class SnippetResponse(
        @SerializedName("publishedAt")
        val publishedAt: String,
        @SerializedName("channelId")
        val channelId: String,
        @SerializedName("title")
        val title: String,
        @SerializedName("description")
        val description: String,
        @SerializedName("thumbnails")
        val thumbnails: ThumbnailsResponse,
        @SerializedName("channelTitle")
        val channelTitle: String,
        @SerializedName("liveBroadcastContent")
        val liveBroadcastContent: String,
        @SerializedName("publishTime")
        val publishTime: String,
    )
    
    data class ThumbnailsResponse(
        @SerializedName("default")
        val default: ThumbnailResponse,
        @SerializedName("medium")
        val medium: ThumbnailResponse,
        @SerializedName("high")
        val high: ThumbnailResponse
    )
    
    data class ThumbnailResponse(
        @SerializedName("url")
        val url: String,
        @SerializedName("height")
        val height: Int,
        @SerializedName("width")
        val width: Int
    )

     

    4. DataSource 만들기

    가장 중요한 통신을 위한 메서드를 만들어야 합니다.

    요청은 아래 주소로 하면 된다고 합니다.

     

    search 뒤쪽은 기본 주소로 깔고 갈거기 때문에 함수 위에 @Get("search") 어노테이션만 적어주면 됩니다.

    인자에는 query와 apiKey는 필수로 넣어주시고 나머지는 사이트를 참조하여 원하시는걸 넣어주시면 됩니다.

    여기서 @Query 어노테이션은 쿼리 날리기 위해 사용됩니다.

    ex) @Query("key") 는 HTTP 통신에 key 쿼리를 날리기 위해 사용됩니다.

    interface SearchDataSource {
    
        @GET("search")
        suspend fun getSearch(
            @Query("q") query: String, // 검색 쿼리
            @Query("maxResults") maxResults: Int = 10,
            @Query("type") type: String = "video",
            @Query("part") part: String = "snippet",
            @Query("key") apiKey: String = BuildConfig.YOUTUBE_API_KEY // 유튜브 API Key를 넣어주시면 됩니다.
        ): SearchResponse
    }

     

    5. Retrofit 연결해주기

    아래처럼 Retrofit과 OkHttpClient를 만들어 연결해주시면 됩니다.

    object YoutubeRetrofitClient {
    
        // 통신할 URL
        private const val YOUTUBE_API_BASE_URL = "https://www.googleapis.com/youtube/v3/"
    
        private val okHttpClient by lazy {
            OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS) // API 연결을 최대 20초까지 시도
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .build()
        }
    
        private val retrofit by lazy {
            Retrofit.Builder()
                .baseUrl(YOUTUBE_API_BASE_URL) // 통신할 URL
                .client(okHttpClient) // OkHttpClient 연결
                .addConverterFactory(GsonConverterFactory.create()) // JSON 통신을 위해 Gson 연결
                .build()
        }
    
        // DataSource 생성
        val searchDataSource: SearchDataSource by lazy {
            retrofit.create(SearchDataSource::class.java)
        }
    }

     

    6. 사용법

    API 테스트이기 때문에 Repository는 따로 만들지 않았습니다.

    class RetrofitTest {
    
        @Test
        fun retrofit_test() = runBlocking {
            YoutubeRetrofitClient.searchDataSource.getSearch("농구").items.forEach {
                println(it)
            }
        }
    }

     

    아래처럼 데이터가 정상적으로 나오게 되는걸 볼 수 있습니다!

    이제 해당 데이터를 가공하여 원하는 UI에 적용시켜서 만들면 될 것 같습니다!

     

Designed by Tistory.