💻 개인공부 💻/Java

공공 데이터 API + JAVA 소스코드

공대생 배기웅 2020. 8. 13. 16:14
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package patient;
 
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
 
import java.io.BufferedReader;
import java.io.IOException;
 
public class ApiExplorer {
 
    private static String getTagValue(String tag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        if(nValue == null
            return null;
        return nValue.getNodeValue();
    }
 
    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
        String url = "http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?ServiceKey=서비스키";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(url);
 
        doc.getDocumentElement().normalize();
        System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
        
        NodeList nList = doc.getElementsByTagName("body");
        //System.out.println(nList);
        
        for(int temp = 0; temp < nList.getLength(); temp++){        
            Node nNode = nList.item(temp);
            if(nNode.getNodeType() == Node.ELEMENT_NODE){
                                
                Element eElement = (Element) nNode;
                System.out.println("######################");
                //System.out.println(eElement.getTextContent());
                System.out.println("확진자 수  : " + getTagValue("decideCnt", eElement));
                System.out.println("사망자 수  : " + getTagValue("deathCnt", eElement));
                System.out.println("검사 진행 수 : " + getTagValue("examCnt", eElement));
                System.out.println("격리 해제 수  : " + getTagValue("clearCnt", eElement));
                System.out.println("치료중 환자 수 : " + getTagValue("careCnt", eElement));
            }    // for end
        }
    }
    
}
cs
728x90
반응형