develop에서 분기하여 feature/stock-price-db 브랜치를 생성하였다.
공공데이터 포털에서 '금융위원회_주식시세정보' 데이터를 활용하기로 하였다.
공공데이털 포탈에서 restful api를 사용할려면 API키를 이용해야한다. 발급받은 키를 스프링에 추가해서 사용하자!
src/main/resources/에 파일을 생성 한 후, 아래와 같이 작성한다.
#공공데이터 포탈 API KEY
data-portal-key = ????
이 후, application.properties에 다음을 추가한다.
#API KEYS
spring.profiles.include=API-KEY
### API KEY ###
application-API-KEY.properties
@Value("${data-portal-key}")
private String dataPortalKey;
@Value("${data-portal-key}")
private String dataPortalKey;
String dataPortalUrl = "https://apis.data.go.kr/1160100/service/GetStockSecuritiesInfoService/getStockPriceInfo?serviceKey=";
public String getJsonFromUrl(String urlstr) {
BufferedReader br = null;
try {
URL url = new URL(urlstr);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), StandardCharsets.UTF_8));
String result;
String line;
for (result = ""; (line = br.readLine()) != null; result = result + line) {
}
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "";
}
public String test(){
return getJsonFromUrl(dataPortalUrl + dataPortalKey + "&numOfRows=10000&resultType=json&basDt=20231130");
}
HttpURLConnection을 사용해서 get 요청을 보내는 작업을 수행 하였다. 최근에는 resttemplate과 WebClient을 많이 사용한다고 한다. 일단은 파이썬으로 수집한 증권 정보 json 파일이 있고 사용할 것이기 때문에 추후 resttemplate과 WebClient로 수정할 예정이다. 다음은 파일에서 json을 불러오는 코드이다.
public String getJsonFromFile(String filePath) {
try {
ClassPathResource resource = new ClassPathResource(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
String result;
String line;
for (result = ""; (line = br.readLine()) != null; result = result + line) {
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
내가 필요한 정보는 "response" > "body" > "items" > "item"이다. 이 중에서, "item"의 경우만 Json Array의 구조이고 나머지는 Object이다.
기존에 사용한 경험이 있는 gson을 이용해서 파싱하기로 하였다. Gson github 해당 페이지를 참고하여 의존성을 추가하였다.
public void parseJson(String json) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
JsonArray itemsArray = jsonObject.getAsJsonObject("response")
.getAsJsonObject("body")
.getAsJsonObject("items")
.getAsJsonArray("item");
System.out.println(itemsArray.get(1));
}
성공적으로 파싱에 성공하였다. 다음에는 주식 가격 정보 객체를 생성하고 파싱한 후, 저장하는 부분을 구현하겠다~!