깨알 개념/Android

[Android] Retrofit - 배경과 구조

interfacer_han 2024. 5. 28. 15:45

#1 Restrofit의 배경

#1-1 REST API

 

REST API (REpresentational State Transfer Application Programming Interface)

#1 무엇(What)에 대한 API인가?#1-1 개요REST(REpresentational State Transfer) 또는 RESTful API는 서버의 자원(Resource)을 두고, 클라이언트와 서버 간의 통신 방법을 규정하는 API(Application Programming Interface)다. 자

kenel.tistory.com

먼저, 클라이언트-서버 간 통신에서 사용되는 REST API에 대해 알아야 한다.

 

#1-2 OkHttp

 

Overview - OkHttp

OkHttp HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an HTTP client that’s efficient by default: HTTP/2 support allows all requests to

square.github.io

예전 안드로이드에서는 클라이언트-서버 간 통신을 위한 라이브러리로 HTTP 프로토콜을 사용하는 OkHttp를 썼다.

 

#1-3 Restrofit

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

이후, Retrofit이 출시됐다. Retrofit은 OkHttp을 기반으로 설계되었기 때문에, 내부적으로는 OkHttp과 똑같이 작동한다. 하지만, Retrofit은 OkHttp에 비해 더 쉽고 효율적이며 REST API에 친화적이다. 

 

#2 안드로이드에서의 Retrofit 구조

#2-1 도식도와 종속성

화살표는 클래스 간의 종속성을 나타낸다. 예를 들어, Retrofit Instance는 Service Interface에 종속된다. 종속의 사전적 의미는 '자주성이 없이 주가 되는 것에 딸려 붙음'이다. 종속은 '알아야 한다'라는 말로도 표현할 수 있다. 따라서 Retrofit Instance는 Service Interface에 대해 알아야 한다. 반면, Service Interface Retrofit Instance를 몰라도 된다. Service Interface을 설계할 땐 Retrofit Instance에서 뭘 어떻게 할지 전혀 신경쓰지 않아도 된다는 것이다 (대신, Service Interface은 Data class에 대해 종속적이므로 Data class를 참조하며 설계해야 한다). Retrofit Instance를 설계할 땐 Service Interface을 알아야 한다. '알아야 하는 쪽'에서 '몰라도 되는 쪽'으로 화살표를 이은 것이 위 도식도다.

 

아래는 각 요소에 대한 설명이다.

 

#2-2 Data class

REST API는 자원(Resource)에 기반한다. 따라서, 서버와 주고 받을 자원을 data class의 형태로 먼저 정의한다.

 

#2-3 Service Interface

HTTP 메소드와 함께 다룰 자원의 위치(이 게시글의 #2-2 참조)를 메소드의 형태로 하나씩 기술한다.

 

#2-4 Retrofit Instance

Retrofit의 인스턴스는 Retrofit.Builder()라는 빌더 클래스를 통해 생성된다. Service Interface에서 기술했던 '다룰 자원의 위치'에 대해 그 기반이 되는 기본 URL과 서버로부터 받은 JSON 등의 파일 형식을 코틀린 객체로 바꿔주는 Converter를 Retrofit.Builder()에 달아준 다음 인스턴스를 생성한다.

 

생성된 Retrofit의 인스턴스는 Service Interface를 매개변수로 받는 Retrofit.create() 메소드를 통해 Service Interface의 구현체(Service Class)를 만든다. 그리고 이 구현체의 메소드들(= Service Interface에서 정의했던 메소드들)로 서버와 통신한다.

 

#3 요약

Retrofit은 클라이언트-서버 간 통신을 간편히 구현하는 도구다.