개요
이번 프로젝트에서 한글 단어를 입력받으면 그에 대한 자세한 뜻을 반환해주는 기능이 필요했다.
따라서 국립국어원 API를 사용하고자 하였는데, 기존에 사용하였던 API들과는 다르게 요청 URL에 필수항목들을 추가하여 요청을 보내야만 하였다.
따라서 기존에 API요청 틀처럼 사용하던 코드들을 다소 수정하였는데, 이 과정에서 다소 애를 먹었다.
URL에 필수항목들을 추가하여 보내야 하는 이유는 국립국어원에서 GET요청으로 받고 있기 때문에 Body에 정보를 첨부하지 못하기 때문인듯 하다.
사용 코드
서비스
public String getDefinition(String word) { String url = "https://stdict.korean.go.kr/api/search.do?key=" + apiKey + "&q=" + word + "&type_search=search" + "&req_type=json"; // 요청 URL HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers); ResponseEntity<ResponseDictDto> response = restTemplate.exchange(url, HttpMethod.GET, entity, ResponseDictDto.class); if (response.getBody() != null && response.getBody().getChannel() != null && !response.getBody().getChannel().getItem().isEmpty()) { return response.getBody().getChannel().getItem().get(0).getSense().getDefinition(); } else { return "No definition found for the word: " + word; } }DTO
public class ResponseDictDto { private Channel channel; @Getter @Setter public static class Channel { private int total; private int num; private String title; private int start; private String description; private List<Item> item; } @Getter @Setter public static class Item { private String sup_no; private String word; private Sense sense; private String pos; } @Getter @Setter public static class Sense { private String definition; private String link; private String type; } }일단 간단히 한글 단어를 입력받으면 사전의 가장 위에 나오는 뜻을 반환하였는데, 추후 모든 단어의 뜻들을 반환하고, 사용자가 선택하여 저장하게끔 로직을 수정할 예정이다.
수정할 때는 해당 DTO로 받은 상태에서 DTO의 Sense의 definition들을 List형태로 반환하면 될듯 하다.