250x250
syk531
하루
syk531
전체 방문자
오늘
어제
  • 분류 전체보기 (166)
    • 개발 (166)
      • java (11)
      • kotlin (7)
      • spring, spring boot (35)
      • Javascript (4)
      • Tyhmeleaf (2)
      • Kafka (17)
      • Docker (8)
      • Kubernetes (3)
      • Elastic Stack (4)
      • react native (3)
      • Web (4)
      • GIS (3)
      • 리눅스 (16)
      • Windows (2)
      • 네트워크 (2)
      • 안드로이드앱 (5)
      • git (2)
      • Tool (15)
      • 프로젝트 (7)
      • 백준알고리즘 (14)
      • DB (2)

인기 글

최근 글

블로그 메뉴

    공지사항

    태그

    • 뉴스앱
    • 오블완
    • 티스토리챌린지

    최근 댓글

    티스토리

    hELLO · Designed By 정상우.
    syk531

    하루

    개발/java

    Retrofit으로 여러개의 API를 하나의 DTO 객체로 처리하는 방법

    2023. 8. 13. 23:14
    728x90
    반응형

    Retorfit : Android와 Java에서 HTTP 통신을 위해 사용하는 라이브러리

    Interface, Retrofit Class, Call로 구성됨

     

    Interface : HTTP API 선언

    Retrofit Class : Interface의 구현을 생성함

    Call : Retrofit Class로 생성된 interface를 사용해서 생성함, 동기 or 비동기 HTTP 요청을 호출함

     

    ● Interface

    public interface CounselApiInterface {
        @GET("selectCounselListApi")
        Call<Counsel> searchCounselList(@Query("page") int page, @Query("perPage") int perPage);
    }

     

    ● Retrofit Class, Call

    @Component
    public class CounselApi {
        private CounselApiInterface counselApiInterface = new Retrofit.Builder()
                                                            .baseUrl("https://localhost:8081/")
                                                            .addConverterFactory(GsonConverterFactory.create())
                                                            .build()
                                                            .create(CounselApiInterface.class);
    
        public Counsel searchCounselList(int page, int perPage) throws Exception {
            Call<Counsel> counselList = counselApiInterface.searchCounselList(page, perPage);
            try {
                Response<Counsel> response = counselList.execute();
    
                if (response.isSuccessful()) {
                    return response.body();
                } else {
                    throw new RuntimeException(response.raw().toString());
                }
            } catch(IOException e) {
                throw new IOException(e);
            } catch(Exception e) {
                throw new Exception(e);
            }
        }
    }

    Retrofit 클래스를 사용해서 interface의 구현을 생성할 때 사용한 .addConverterFactory(GsonConverterFactory.create()) 코드는 HTTP Body를 역직렬화 하는데 Gson을 사용한다는 의미이다. 해당 코드로 인해서 HTTP Body를 원하는 DTO 객체로 받을 수 있게 된다.

     

    ● DTO

    @Getter
    @Setter
    public class Counsel {
        @SerializedName("상담번호")
        private String counselId;
        @SerializedName(value = "연락처", alternate = {"전화", "전화번호"})
        private String tellNo;
        @SerializedName("제목")
        private String title;
        @SerializedName("내용")
        private String content;
    }

    API 응답값의 key와 DTO의 멤버변수의 이름이 다를때 @SerializedName("key") 를 통해서 API 응답값의 key의 값을 DTO의 멤버변수로 받을 수 있다.(이름이 같으면 필요없음)

    (ex. API 응답값의 key가 상담번호인 값을 Counsel DTO의 counselId 멤버변수로 받음)

    DTO의 동일한 멤버변수가 여러 API의 다른 key값을 받고 싶으면 alternate 추가요소를 사용하면 된다.

    (ex. Counsel DTO의 tellNo 멤버변수는 API 응답값의 key가 연락처, 전화, 전화번호인 값을 받을 수 있음)

     

    ● 참고자료

    https://square.github.io/retrofit/

    https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.0/com/google/gson/annotations/SerializedName.html

     

    728x90
    반응형
    저작자표시 (새창열림)

    '개발 > java' 카테고리의 다른 글

    [Java] byte 에서 특정자리 bit 추출하는 방법  (0) 2024.02.02
    Google Bard API 사용  (0) 2023.12.02
    org.apache.commons.lang3.ObjectUtils max 함수  (0) 2023.10.06
    Junit - MockServletContext 사용  (0) 2023.09.06
    eclipse spotbugs (findbugs)  (0) 2023.04.26
      '개발/java' 카테고리의 다른 글
      • Google Bard API 사용
      • org.apache.commons.lang3.ObjectUtils max 함수
      • Junit - MockServletContext 사용
      • eclipse spotbugs (findbugs)
      syk531
      syk531
      기억을 위해 기록을.

      티스토리툴바