Retrofit은 대표적인 안드로이드 통신 라이브러리이다.

callback을 통해서 Main Thread에서 UI 업데이트를 간단하게 할 수 있도록 제공 해준다.

Retroft 사용 방법

  1. 서버에 request를 보내면 서버에서 reponse 값을 주는데 그 response값을 처리 해야할 kotlin data class를 만들어야 한다.
  2. HTTP 작업을 정의 하는 API Interface를 만들어야 한다.
  3. Retrofit. Builder 클래스를 만든다.

위 3가지 과정을 통해 API Interface의 메서드 객체를 선언하고 동기/비동기로 실행하여 서버에서 response값을 받아온 뒤 작업을 수행합니다.

그럼 어떻게 API 인터페이스를 구현 해서 request를 날릴 수 있을까?

var apiService: APIService = retrofit.create(ApiService::class.java)

위 코드 .create 메서드를 살펴 보면 다음과 같다.

API 서비스 객체를 만들 때 다음과 같이 동작하는데

// Create an implementation of the API endpoints defined by the {@code service} interface
public <T> T create(final Class<T> service) {
    validateServiceInterface(service);
    return (T)
        Proxy.newProxyInstance(
            service.getClassLoader(),
            new Class<?>[] {service},
            new InvocationHandler() {
              private final Platform platform = Platform.get();
              private final Object[] emptyArgs = new Object[0];

              @Override
              public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args)
                  throws Throwable {
                // If the method is a method from Object then defer to normal invocation.
                if (method.getDeclaringClass() == Object.class) {
                  return method.invoke(this, args);
                }
                args = args != null ? args : emptyArgs;
                return platform.isDefaultMethod(method)
                    ? platform.invokeDefaultMethod(method, service, proxy, args)
                    : loadServiceMethod(method).invoke(args);
              }
            });
  }

주석의 내용을 보면 인터페이스에 정의된 API 엔드포인트들의 구현체를 만든다라고 적혀있다.

엔드포인트란 커뮤니케이션을 가능하게, API가 서버에서 리소스에 접근할 수 있도록 가능하게 하는 URL입니다.

대부분 BASE URL 기반으로 뒤에 /로 시작하는 부분이다.