API와 Service Key를 사용하여 POSTMAN에서 GET 요청을 해보니 다음과 같은 XML 데이터가 보였다.
XML
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@RestController
public class RestTestController {
@GetMapping("/apitest")
public String callApiWithXml() {
StringBuffer result = new StringBuffer();
try {
String apiUrl = "http://apis.data.go.kr/B552584/EvCharger/getChargerInfo?" +
"serviceKey=[Service Key]" +
"&numOfRows=10" +
"&pageNo=4";
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String returnLine;
result.append("<xmp>");
while((returnLine = bufferedReader.readLine()) != null) {
result.append(returnLine + "\n");
}
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result + "</xmp>";
}
}
위와 같이 데이터가 잘 보이는 것을 확인할 수 있었다.
공공 데이터는 대부분 XML로 제공된다.
요즘은 대부분 JSON을 사용하기 때문에 JSON으로 바꾸는 작업도 진행하였다.
JSON
import org.json.JSONObject;
import org.json.XML;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@RestController
public class RestTestController {
@GetMapping("/jsonapi")
public String callApiWithJson() {
StringBuffer result = new StringBuffer();
String jsonPrintString = null;
try {
String apiUrl = "http://apis.data.go.kr/B552584/EvCharger/getChargerInfo?" +
"serviceKey=[Service Key]" +
"&numOfRows=10" +
"&pageNo=4";
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
BufferedInputStream bufferedInputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream, "UTF-8"));
String returnLine;
while((returnLine = bufferedReader.readLine()) != null) {
result.append(returnLine);
}
JSONObject jsonObject = XML.toJSONObject(result.toString());
jsonPrintString = jsonObject.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jsonPrintString;
}
}