[android] 안드로이드에서 Retrofit 라이브러리 사용하기

소개

안드로이드 앱에서 웹 서버와 통신하기 위해서는 Retrofit 라이브러리를 사용할 수 있습니다. Retrofit은 RESTful API와의 통신을 간편하게 처리할 수 있는 라이브러리로, 안드로이드 앱 개발에 매우 유용합니다.

Retrofit 라이브러리 추가

먼저, Retrofit 라이브러리를 안드로이드 프로젝트에 추가해야 합니다. 이를 위해서는 build.gradle 파일에 Retrofit 종속성을 추가해야 합니다.

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // JSON 데이터 파싱을 위한 Gson 컨버터
}

위의 코드에서, retrofit은 Retrofit 라이브러리를 의미하고, converter-gson은 JSON 데이터를 쉽게 파싱할 수 있도록 도와주는 Gson 컨버터입니다.

Retrofit 인터페이스 정의

Retrofit을 사용하기 위해서는 API 요청을 정의하는 인터페이스를 생성해야 합니다. 이 인터페이스에는 서버와의 통신을 위한 메서드들을 정의하게 됩니다.

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface MyApiService {
    @GET("users/{user_id}")
    Call<User> getUser(@Path("user_id") int userId);
}

위의 코드에서 MyApiService는 Retrofit 인터페이스이며, getUser 메서드는 서버에서 사용자 정보를 가져오는 GET 요청을 정의하고 있습니다.

Retrofit 인스턴스 생성

Retrofit을 사용하기 위해서는 Retrofit 객체를 생성해야 합니다. 보통은 앱의 초기화 과정에서 Retrofit 객체를 생성하고 이를 통해 API 요청을 처리합니다.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();
MyApiService service = retrofit.create(MyApiService.class);

위의 코드에서 retrofit.create(MyApiService.class)를 통해 MyApiService 인터페이스를 구현한 객체를 생성하고, 이를 통해 서버와의 통신을 처리할 수 있습니다.

네트워크 요청 및 응답 처리

이제 Retrofit을 사용하여 서버에 요청을 보내고 응답을 처리할 수 있습니다. 예를 들어, getUser 메서드를 사용하여 사용자 정보를 가져오는 요청을 보낼 수 있습니다.

Call<User> call = service.getUser(123);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        if (response.isSuccessful()) {
            User user = response.body();
            // 사용자 정보 처리
        } else {
            // 오류 처리
        }
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        // 네트워크 오류 처리
    }
});

위의 코드에서 call.enqueue를 통해 비동기적으로 서버에 요청을 보내고, 서버로부터의 응답을 처리합니다.

이렇게 Retrofit을 사용하면 안드로이드 앱에서 간편하게 서버와의 통신을 처리할 수 있습니다.


참고문헌: