백엔드에서 api 요청 보내기

leverest96·2023년 9월 7일
0

Spring / Java

목록 보기
19/20
post-thumbnail

구현을 하던 도중 카카오 맵에서 정보를 받아와야하는 상황이 생겼다.

하지만 백엔드에서 요청을 또 서버로 보낸다? 처음 겪는 것...

사실 이것 때문에 지난번에 카카오 로그인을 포기한 적이 있는데 드디어 방법 찾은듯?

WebClient를 사용하자!

아래의 예시는 카카오 맵에서 좌표를 통해 주소를 구하는 api를 받아온 것이다.
상황에 맞게 커스텀하자.

@PostConstruct
public void initWebClient() {
    webClient = WebClient.create("https://dapi.kakao.com/v2/local/geo/coord2regioncode.json");
}

private String sendRequest(final double latitude, final double longitude) {
    return webClient.get()
        .uri(uriBuilder -> uriBuilder
            .queryParam("x", latitude)
            .queryParam("y", longitude)
            .build())
        .header("Authorization", "KakaoAK {javascript api 키}")
        .retrieve()
        .bodyToMono(String.class)
        .block();
}

@Getter
private static class RegionJson {
    private Meta meta;
    private List<Document> documents;

    @Getter
    public static class Meta {
        private int total_count;
    }

    @Getter
    public static class Document {
        private String region_type;
        private String code;
        private String address_name;
        private String region_1depth_name;
        private String region_2depth_name;
        private String region_3depth_name;
        private String region_4depth_name;
        private double x;
        private double y;
    }
}

실제 로직상 받아온 json을 풀어서 사용하는 방법

final String regionObject = sendRequest(requestDto.x(), requestDto.y());

final Gson gson = new Gson();

final RegionJson regionJson = gson.fromJson(regionObject, RegionJson.class);

final String region = regionJson.getDocuments().get(0).address_name;
profile
응애 난 애기 개발자

0개의 댓글