Backend
home
🈹

ApiExecutor 분리 - 인터페이스 도입과 클래스 분리

생성일
2025/01/24 05:52
태그
ApiExecutor 인터페이스 생성
package tobyspring.hellospring.api; import java.io.IOException; import java.net.URI; public interface ApiExecutor { String execute(URI uri) throws IOException; }
Java
복사
SimpleApiExecutor 클래스 생성
package tobyspring.hellospring.api; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URI; import java.util.stream.Collectors; public class SimpleApiExecutor implements ApiExecutor { @Override public String execute(URI uri) throws IOException { String response; HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { response = br.lines().collect(Collectors.joining()); } return response; } }
Java
복사
WebApiExrateProvider 수정
package tobyspring.hellospring.exrate; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import tobyspring.hellospring.api.SimpleApiExecutor; import tobyspring.hellospring.payment.ExRateProvider; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.stream.Collectors; public class WebApiExRateProvider implements ExRateProvider { @Override public BigDecimal getExRate(String currency) { String url = "https://open.er-api.com/v6/latest/" + currency; return runApiForExRate(url); } private static BigDecimal runApiForExRate(String url) { URI uri; // URL -> URI 변경 try { uri = new URI(url); } catch (URISyntaxException e) { throw new RuntimeException(e); } String response; try { response = new SimpleApiExecutor().execute(uri); // 수정 } catch (IOException e) { throw new RuntimeException(e); } // build gradle에서 의존성 추가 // 'com.fasterxml.jackson.core:jackson-databind:2.12.5' try { return extractExRate(response); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } private static BigDecimal extractExRate(String response) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); ExRateData data = mapper.readValue(response, ExRateData.class); return data.rates().get("KRW"); } }
Java
복사