728x90
공공데이터 API를 사용할 때, WebClient 나 RestTemplate class에 Decoding된 Service Key를 사용하면 " SERVICE KEY IS NOT REGISTERED ERROR"가 발생한다. 원인은 정확히는 모르겠지만 Decoding된 Service Key가 Encoding된 후의 값을 실제 비교해 보면 등록된 Service Key 인코딩 키값과 일지하지 않는 거 같다.
그래서 방법을 찾던 중에 에러가 발생하지 않는 방법은 아래와 같이 Encoding된 Service Key를 사용하고 WebClient에서 encoding하지 않도록 하는 방법이다.
public StockInfoDTO getStockInfoWebClient(String name) {
String baseUrl = "https://apis.data.go.kr";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
String apiPath = "/getStockPriceInfo";
String REQUEST_PATH = "/1160100/service/GetStockSecuritiesInfoService" + apiPath;
WebClient webClient = WebClient.builder()
.uriBuilderFactory(factory)
.baseUrl(baseUrl)
.build();
// URI에 포함될 쿼리 파라미터 구성
StockInfoDTO stockInfoDTO;
try {
stockInfoDTO = webClient.get()
.uri(
uriBuilder -> uriBuilder
.path(REQUEST_PATH)
.queryParam("serviceKey", SERVICE_KEY_ENCODE)
.queryParam("resultType", "json")
.queryParam("itmsNm", URLEncoder.encode(name, StandardCharsets.UTF_8))
.build())
.retrieve()
.bodyToMono(StockInfoDTO.class)
.block(); // 동기적으로 결과 받기
System.out.println("API 응답: " + stockInfoDTO);
return stockInfoDTO;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("API 호출 실패", e);
}
}
SERVICE_KEY_ENCODE 값은 발급받은 Encoding Service Key 문자열이다. 위와 같이 실행하면 Service key 에러없이 동작하는 것을 확인할 수 있다.
728x90
'Research > Programming' 카테고리의 다른 글
Failed to resolve: com.tickaroo.tikxml:annotation:0.8.15 (1) | 2024.10.30 |
---|---|
Deploy a Google Apps Script as a web app with a same URL on each deploy. (1) | 2024.10.22 |
*.java를 빌드해서 실행가능한 *.jar를 만드는 법 (0) | 2023.09.21 |
/bin/sh: 1: Syntax error: Bad fd number (0) | 2013.01.19 |
cross compile configure시에 build, host, target option (0) | 2012.10.29 |