업데이트:

카테고리:

/

태그: , ,

Retrofit

웹 서비스와 통신하기 위해서는 vue / react 에서는 axios를 사용한 것 처럼 안드로이드에는 Retrofit2 가 필요하다.

  1. 인터넷 Permission 설정

    manifest 에 아래 코드를 작성한다.

    핸드폰의 인터넷 통신이 되야 retrofit을 통해서 서버와 통신이 가능해진다.

     <user-permission android:name="android.permission.Internet"/>
    
  2. 의존성 추가
    • 'com.squareup.retrofit2:retrofit:version' - Retrofit
    • 'com.squareup.retrofit2:converter-scalars:version' - Json ↔ Gson
  3. Java 8 추가

     complieoptions {
     	sourceCompatibility JavaVersion.Version_1_8
     	targetCompatibility JavaVersion.Version_1_8
     }
     KotlinOptions {
     	jvmTarget = JavaVersion.Version_1_8.toString()
     }
    
  4. Retrofit 객체 생성

     val retrofit = Retrofit.Builder()
     	// 변환 방식
     	.addConverterFactory(GsonConverterFactory.create())
     	// 통신할 인터넷의 기본 url
     	.baseUrl(BASE_URL)
     	.build()
    
  5. 요청 url을 담은 interface 설정

     interface apiService {
     	@GET("realstate")
     	fun getData()
     	: Call<String>
        
     	...
     }
    

    요청을 보낼 url과 알맞은 http method 를 함수 형태로 작성한다.

    함수의 리턴타입 - Call 은 retrofit의 응답 결과 타입이다.

  6. 요청 보내고 응답 받기

     private suspend fun getDataAtInternet() {
     	Coroutine(Dispatcher.IO).launch {
     		try {
     			val result = retrofit.apiService.getData()
     			// 요청 성공 시
     			return result.excute() 
     		} catch ( e: Exception ) {
     			// 요청 실패 시 
     		}
     	}	
     }
    

Moshi

이때 데이터는 Json 타입으로 넘어와서 Gson을 통해서 한번 값을 변환하고 이후 호출하는 함수 내부에서 해당하는 dataType으로 한번 더 변환을 한다.

이런 2번의 변환 없이 바로 Kotlin 객체로 변환시켜주는 것이 Moshi 라이브러리 이다.

  1. 의존성 추가
    • com.squareup.moshi:moshi-kotlin${version}
    • com.squareup.retrofit2:converter-moshi:version
  2. 데이터 타입 추가

    응답 받는 데이터는 data class 상단에 JsonClass(autoGenerate=true) 를 작성해야된다.

     @JsonClass(autoGenerate=true)
     data class example (
     	@Json(name = "count") val count: Int
     	@field:Json(name = "properties") val properties: List<property>
     )
    

    @Json 내부에 있는 값은 실제로 응답 받는 데이터의 필드와 같아야한다.

  3. retrofit 선언 변경

     private val moshi = Moshi.Builder()
     	.add(KotlinJsonAdapterFactory())
     	.build()
        
     private val retrofit = Retrofit.Builder()
     	.addConverterFactory(MoshiConvertFactory(moshi))
     	.baseUrl(BASE_URL)
     	.build()
    

OKHttp

처음에는 이름만 보고 https와의 통신도 가능하게 만드는 것인가… 라는 생각을 했지만 그게 아닌 예측가능한 결과를 보내 Type-safe 하게 코드를 짤 수 있도록 한다.

Retrofit만 단독으로 사용할 경우 별도의 변환과정 없이도 바로 사용할 수 있다.

OKHttp와 같이 사용한다면 JSON 객체를 본인이 사용할 타입으로 변화는 과정이 필수다.