안드로이드 스튜디오

Retrofit2 사용방법

고줭 2021. 8. 26. 00:04

Retrofit2를 사용해서 프로젝트를 했습니다. 서버와의 통신을 위해서 HttpURLConnection이나 Volley, Retrofit2를 사용 할 수 있다고 하는데 HttpURLConnection의 경우 하나하나 커스텀해서 만들어야 하기에 첨에 Volley를 사용했다가 Retrofit2가 사용하기에 편할 것같아 Retrofit2를 사용했습니다.

android studio로 프로젝트를 생성하면 build.gradle이 두개가 있는데 dependencies가 있는 그래들파일에다가 retrofit2와 converter-gson을 implement해줘야 합니다. gson은 통신해서 가져온내용을 파싱하기위한것이니 필수적인 요소입니다.
(def retrofit_version = "2.9.0"   <<<< 굳이 이렇게 안하고 그대로 숫자 넣어도 됩니다.)

retrofit 패키지를 생성하고 RetrofitAPI 인터페이스와 RetrofitClient 클래스를 생성합니다. 이름은 굳이 이럴 필요는 없지만 잘 모르시겠다면 똑같이 적어보시면됩니다.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static final String BASE_URL = "이 곳에 사이트 주소를 적어주세요";

    public static RetrofitAPI getApiService() {
        return getInstance().create(RetrofitAPI.class);
    }

    private static Retrofit getInstance() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

}

RetrofitClient 클래스의 내용입니다 BASE_URL의 끝에는 "   /   " 를 넣어주세요.

나머지 코드는 똑같이 쓰셔야합니다.

import com.samsan.xcapeapplication.vo.HintVO;
import com.samsan.xcapeapplication.vo.MerchantVO;
import com.samsan.xcapeapplication.vo.ThemeVO;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface RetrofitAPI {
    @GET("api/주소/주소")
    Call<List<MerchantVO>> getMerchantList();

    @GET("api/주소/주소")
    Call<List<ThemeVO>> getThemeList(@Query("merchantCode") String merchantCode);

    @GET("api/주소")
    Call<List<HintVO>> getHintList(@Query("merchant") String merchant, @Query("themeCode") String themeCode);
}

어노테이션 보면 대충 아시겠지만 get방식으로 해당 주소를 가져오겠다는 거고 거기에 Call형식의 메소드로 가져옵니다. 가맹점 리스트, 테마 리스트, 힌트 리스트는 전부 리스트형식으로 가져올꺼기 때문에 Call<List<HintVO>>형식이 되는거고 리스트형식이 아니라면 Call<HintVO>형식으로 하시면 됩니다.

@Query 어노테이션은 주소 파라미터값이라 생각하시면 됩니다. 
BASE_URL/api/주소?merchantCode=asdf 이렇게요

/**
  * MainActivity
  */

Call<List<HintVO>> callHintList = getApiService().getHintList(merchantCode, themeCode);
                callHintList.enqueue(new Callback<List<HintVO>>() {
                    @Override
                    public void onResponse(Call<List<HintVO>> call, Response<List<HintVO>> response) {
                        Gson gson = new Gson();
                        
                        // 이 부분이 핵심
                        String test = gson.toJson(response.body());
                    }

 

 

MainActivity에서 실제 통신하는 코드 부분입니다. (실행부에는 SharedPreferences를 사용했기에 String test 부분으로 대체했습니다.)

인터페이스의 정의한 callHintList를 호출하면 callHintList.enqueue(new Callback<List<HintVO>>(){}로 결과값을 받을 수 있습니다.  response.body()를 gson.toJson으로 파싱해야 String값으로 변환할수있습니다.