스크린샷 2024-07-28 오후 11.31.20.png

public class WebApiExRateProvider implements ExRateProvider {
    ApiTemplate apiTemplate = new ApiTemplate();
    
    @Override
    public BigDecimal getExRate(String currency) {
        String url = "<https://open.er-api.com/v6/latest/>" + currency;

        return apiTemplate.getExRate(url, new SimpleApiExecutor(), new ErApiExRateExtractor());
    }
}

public class ApiTemplate {
    public BigDecimal getExRate(String url, ApiExecutor apiExecutor, ExRateExtractor exRateExtractor) {
        URI uri;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        String response;
        try {
            response = apiExecutor.execute(uri);
            System.out.println(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            BigDecimal exRate = exRateExtractor.extract(response);
            System.out.println("API ExRate: " + exRate);
            return exRate;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}

public class HttpClientApiExecutor implements ApiExecutor {
    @Override
    public String execute(URI uri) throws IOException {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(uri)
                .GET()
                .build();

        try (HttpClient client = HttpClient.newBuilder().build()) {
            return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

public class WebApiExRateProvider implements ExRateProvider {
    ApiTemplate apiTemplate = new ApiTemplate();

    @Override
    public BigDecimal getExRate(String currency) {
        String url = "<https://open.er-api.com/v6/latest/>" + currency;

        return apiTemplate.getExRate(url, new HttpClientApiExecutor(), new ErApiExRateExtractor());
    }
}