•
WebApiExRateProvider의 구성
◦
URI를 준비하고 예외처리를 위한 작업을 하는 코드
◦
API를 실행하고, 서버로부터 받은 응답을 가져오는 코드
◦
JSON 문자열을 파싱하고 필요한 환율정보를 추출하는 코드
•
메소드 추출
package tobyspring.hellospring.exrate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
URI uri; // URL -> URI 변경
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
String response;
try {
response = executeApi(uri);
} catch (IOException e) {
throw new RuntimeException(e);
}
// build gradle에서 의존성 추가
// 'com.fasterxml.jackson.core:jackson-databind:2.12.5'
try {
return ParseExRate(response);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static BigDecimal ParseExRate(String response) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ExRateData data = mapper.readValue(response, ExRateData.class);
return data.rates().get("KRW");
}
private static String executeApi(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
복사