유니 코드

[Android/Kotlin] 도서 리뷰 앱 - Retrofit사용 준비 본문

오늘의 공부는?!/Android

[Android/Kotlin] 도서 리뷰 앱 - Retrofit사용 준비

꼬물쥰 2022. 6. 29. 17:40

retrofit이란?

Retrofit은 서버와 클라이언트 간 http 통신을 위한 라이브러리

즉, 안드로이드에서 http 통신을 할 수 있도록 도와주는 라이브러리이다

자세한 설명을 하기에는 글이 길어질 것 같으니 다음에 따로 글을 올려보도록 하겠다


  • gradle 추가
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

retrofit을 사용하기 위해서는 먼저 gradle에 추가를 해줘야한다 (최신버전은 Retrofit GitHub에서 확인)

gson형식으로 변환을 해주는 converter-gson 라이브러리도 추가해주었다

네트워크에서 가져온 string 형태의 json을 바로 gson형태(객체)로 변환을 해준다

 

 

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

서버와 통신하기 위해서 매니페스트에 인터넷 권한을 추가해준다

 

 

  • data class 생성

GET 요청결과(JSON)&nbsp; &nbsp;query = hello

위의 요청결과를 정리하면 아래처럼 표현할 수 있다

ㄴ lastBuildDate
ㄴ total
ㄴ start 
ㄴ display
ㄴ items[0]
    ㄴ title
    ㄴ link
    ㄴ image
    ㄴ author
    ㄴ description
               .
               .
               .        

 

이걸 data class로 바꾸면 아래와 같다

data class SearchDto(
    @SerializedName("lastBuildDate") var lastBuildDate: String,
    @SerializedName("total") var total: Int,
    @SerializedName("start") var start: Int,
    @SerializedName("display") var display: Int,
    @SerializedName("items") val books: List<Book>
)
data class Book(
    @SerializedName("title") val title: String,
    @SerializedName("link") val link: String,
    @SerializedName("image") val image: String,
    @SerializedName("author") val author: String,
    @SerializedName("description") val description: String
)

items는 배열이기 때문에 List로 선언했다

그런데 제공하는 정보를 다 사용할 일은 많이 없고 필요한 정보만 가져다가 쓰면 된다

그럴때는 아래와 같이 필요없는 건 지워버리면 된다

data class SearchDto(
    @SerializedName("items") val books: List<Book>
)
data class Book(
    @SerializedName("title") val title: String,
    @SerializedName("image") val image: String,
    @SerializedName("description") val description: String
)

Json에 정해져 있는 이름을 사용하다보면 변수명이 마음에 안들수도 있다

예를 들어 items 대신에 books를 사용하고 싶으면 

변수 앞에 @SerializedName("")을 붙여 원래 변수명을 넣어주고

변수를 선언할 때 원하는 변수명으로 선언하면된다

 

@SerializedName은 gson 라이브러리에서 제공하는 어노테이션인데

여기서 Serialize는 data class 객체를 JSON 형태로 변환하는 것을 말한다.

@SerializedName을 이용하면 'books'의 직렬화된 이름은 'items' 라는 뜻이 되는 것이다.

이렇게 표시해두면 GSON converter가 JSON을 받아와서 어노테이션을 보고 'items'값을 'books'에 매핑해준다.

 

  • 인터페이스 정의
interface BookService {
    @GET("v1/search/book.json")
    fun getBooksByName(
        @Header("X-Naver-CLient-Id") clientId: String,
        @Header("X-Naver-CLient-Secret") clientSecret: String,
        @Query("query") query: String
        ) : Call<SearchDto>
}

위와 같은 API 인터페이스를 만들어야된다

이 인터페이스는 내가 어떤 요청을 어떻게 보낼건지 메서드를 정의해주는 것이다

 

interface BookService {
    @GET("v1/search/book.json")
    fun getBooksByName(
        @Header("X-Naver-CLient-Id") clientId: String,
        @Header("X-Naver-CLient-Secret") clientSecret: String,
        @Query("query") query: String) : Call<SearchDto>
}

보내는 요청의 형태에는 GET, POST, PUT, DELETE 총 4가지가 있다

우리는 검색하고 조회만  하기 때문에 GET을 사용한다

 

GET  데이터 검색이나 조회
POST  데이터 추가
PUT  데이터 수정
DELETE  데이터 삭제

 

interface BookService {
    @GET("v1/search/book.json")
    fun getBooksByName(
        @Header("X-Naver-CLient-Id") clientId: String,
        @Header("X-Naver-CLient-Secret") clientSecret: String,
        @Query("query") query: String) : Call<SearchDto>
}

https://openapi.naver.com/v1/search/book.json?query=hello

파란색은 BaseUrl 빨간색은 EndPoint 초록색은 Parameter로 구분할 수 있다

어노테이션 안에는 EndPoint를 넣어주면 된다

 

interface BookService {
    @GET("v1/search/book.json")
    fun getBooksByName(
        @Header("X-Naver-CLient-Id") clientId: String,
        @Header("X-Naver-CLient-Secret") clientSecret: String,
        @Query("query") query: String) : Call<SearchDto>
}

헤더에는 client id와 client secret을 포함해주어야하므로 @Header를 이용해서 헤더에 포함시켜야한다

query는 동적으로 변경해야하는 파라미터라서 @Query를 이용해 메서드 호출시 값을 넘겨받아 주소에 포함해준다

 

interface BookService {
    @GET("v1/search/book.json")
    fun getBooksByName(
        @Header("X-Naver-CLient-Id") clientId: String,
        @Header("X-Naver-CLient-Secret") clientSecret: String,
        @Query("query") query: String) : Call<SearchDto>
}

retrofit의 리턴형인 Call<>안에 반환형을 적어주면 된다

우리는 아까 생성한 data class인 SearchDto를 적어주면 된다

 

다음 글에서는 Retorfit을 사용해보겠다,,,,!

Comments