참고영상 : https://www.youtube.com/watch?v=coBTVyj-Ef8&list=PLgICV6Wc1orOrVamkpfmxo44LFw2C1YJZ&index=7
데이터
도서관정보나루 인기대출도서 API: https://www.data4library.kr/loanDataL
추가할 내용
- 검색조건에 따라 url이 변경되도록 처리하기
package part06;
import java.io.BufferedInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Scanner;
public class SearchPopularbookXml {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
Scanner sc = new Scanner(System.in);
System.out.print("입력 (남성0, 여성1) :");
String a = sc.nextLine();
String encode="";
encode = URLEncoder.encode(a,"UTF-8");
//파싱할 InputStream생성
DocumentBuilder builder = factory.newDocumentBuilder();
//1. 웹서버를 제공하는 url에 연결해서 데이터 가져오기
//1) 접속할 url정보 정의(popularBook_url)
StringBuffer popularBook_url = new StringBuffer();
String key= " **개인 인증키 입력** ";
popularBook_url.append("http://data4library.kr/api/loanItemSrch");
popularBook_url.append("?authKey="+key);
popularBook_url.append("&startDt=2023-01-01");
popularBook_url.append("&endDt=2023-02-27");
popularBook_url.append("&gender="+encode);
System.out.println(popularBook_url);
//2) 웹서버에 접속하기
URL url = new URL(popularBook_url.toString());
//3) 접속해서 response되는 데이터 읽어오기
//읽어온 데이터저장 - BufferedInputStream은 InputStream의 하위
BufferedInputStream xmldata = new BufferedInputStream(url.openStream());
Document document = builder.parse(xmldata);
//데이터 읽어오기 (root element : docs)
Element root = document.getDocumentElement();
System.out.println(root.getTagName());
NodeList list = root.getElementsByTagName("doc");
System.out.print("조회갯수 : "+ list.getLength()+"\n");
System.out.println();
for(int i=0; i<list.getLength(); i++) {
Node node = list.item(i);
NodeList node_childList = node.getChildNodes();
for(int j=0; j<node_childList.getLength(); j++) {
Node item_child = node_childList.item(j);
System.out.println(item_child.getNodeName()+" : "+item_child.getTextContent());
}
System.out.println();
}
}catch(Exception e) {
e.printStackTrace();
}
}//main
}//end class