본문 바로가기

개발 이야기

Android RESTful 개발 Java 코드

320x100

Android 앱 개발에서 RESTful API를 사용하는 것은 매우 일반적이며 중요한 기능입니다. RESTful API를 이용한 개발에 Retrofit 라이브러리와 같은 강력한 라이브러리를 추천합니다. Retrofit은 간편한 구성으로 높은 생산성을 제공하며, 대부분의 Android 개발자들이 참조 및 사용하는 인기 라이브러리입니다.

  1. 프로젝트에 Retrofit 라이브러리 추가:
    프로젝트의 build.gradle 파일의 dependencies 블록에 다음 라이브러리를 추가하세요.
dependencies {
    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    // OkHttp (로깅과 인터셉터를 사용하기 위해)
    implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'
    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'
}
  1. REST API 인터페이스 정의:
    Retrofit을 사용할 때 API의 종류에 맞게 인터페이스를 정의합니다. 예를 들어, 다음과 같이 ApiService 인터페이스를 만들 수 있습니다.
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiService {
    @GET("your/endpoint/path")
    Call<ResponseBody> getSomeData();
}
  1. Retrofit 인스턴스 생성:
    Retrofit 인스턴스를 생성하고 해당 서버에 요청 위한 설정을 만듭니다. 이를 위해 별도의 클래스 ApiClient를 만들어 설정을 진행합니다.
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addInterceptor(loggingInterceptor);

            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();
        }
        return retrofit;
    }
}
  1. API 호출 및 응답 처리:
    이제 새로 생성한 ApiClient 클래스를 사용해 API 호출을 진행하고 결과를 처리합니다.
public class MainActivity extends {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ApiService apiService = ApiClient.getClient("https://api.example.com/").create(ApiService.class);
        Call<ResponseBody> call = apiService.getSomeData();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    // 여기에서 result를 처리합니다.

                } else {
                    // 오류에 대해 처리합니다.
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // 통신 실패에 대해 처리합니다.
            }
        });
    }
}

이렇게 Retrofit 라이브러리를 사용해 RESTful API를 쉽게 호출하고 결과를 처리할 수 있습니다. 해당 코드를 참고하여 필요한 기능과 인터페이스를 조정하여 프로젝트에 적용할 수 있습니다. 원활한 개발을 위해 필요한 경우 인터셉터, 인증, 헤더 등을 추가할 수 있습니다.

반응형