티스토리 뷰
네이버 검색 OPEN API를 활용하기
목 표
책 검색 api의 url에 적절한 파라미터를 세팅해 요청을 보내고 xml형식으로 돌아오는 응답을 잘 읽어서 원하는 정보를 추출
자바코드로 어떻게 url에 요청을 보내고 응답을 읽을 수 있는지.. xml문서에 원하는 값을 어떻게 획득할 수 있는지..
순 서
1. 모델 클래스 생성
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | package model; public class Book { private String title; private String link; private String image; private String author; private String price; private String discount; private String publisher; private String pubdate; private String isbn; private String description; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getDiscount() { return discount; } public void setDiscount(String discount) { this.discount = discount; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPubdate() { return pubdate; } public void setPubdate(String pubdate) { this.pubdate = pubdate; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Book [title=" + title + ", link=" + link + ", image=" + image + ", author=" + author + ", price=" + price + ", discount=" + discount + ", publisher=" + publisher + ", pubdate=" + pubdate + ", isbn=" + isbn + ", description=" + description + "]"; } } | cs |
2. api 서비스 클래스 생성 ( api 설정, 파싱작업 )
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | package service; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import model.Book; public class NaverBookService { private static String clientID = "wla82tmYgxtmxGQuvyrO"; //api 사용 신청시 제공되는 아이디 private static String clientSecret = "ZTMk48WHjf"; //패스워드 public List<Book> searchBook(String keyword, int display, int start) { URL url; List<Book> list = null; try { url = new URL("https://openapi.naver.com/v1/search/book.xml?query=" + URLEncoder.encode(keyword, "UTF-8") + (display != 0 ? "&display=" + display : "") + (start != 0 ? "&start=" + start : "")); URLConnection urlConn; //url 연결 urlConn = url.openConnection(); urlConn.setRequestProperty("X-naver-Client-Id", clientID); urlConn.setRequestProperty("X-naver-Client-Secret", clientSecret); //파싱 - 팩토리 만들고 팩토리로 파서 생성 (풀 파서 사용) XmlPullParserFactory factory; factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput((new InputStreamReader(urlConn.getInputStream()))); int eventType = parser.getEventType(); Book b = null; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.END_DOCUMENT: // 문서의 끝 break; case XmlPullParser.START_DOCUMENT: list = new ArrayList<Book>(); break; case XmlPullParser.START_TAG: { String tag = parser.getName(); switch (tag) { case "item": b = new Book(); break; case "title": if (b != null) b.setTitle(parser.nextText()); break; case "link": if (b != null) b.setLink(parser.nextText()); break; case "image": if (b != null) b.setImage(parser.nextText()); break; case "author": if (b != null) b.setAuthor(parser.nextText()); break; case "discount": if (b != null) b.setDiscount(parser.nextText()); break; case "publisher": if (b != null) b.setPublisher(parser.nextText()); break; case "pubdate": if (b != null) b.setPubdate(parser.nextText()); break; case "isbn": if (b != null) b.setIsbn(parser.nextText()); break; case "description": if (b != null) b.setDescription(parser.nextText()); break; } break; } case XmlPullParser.END_TAG: { String tag = parser.getName(); if (tag.equals("item")) { list.add(b); b = null; } } } eventType = parser.next(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } } | cs |
3. 테스트
1 2 3 4 5 6 7 8 9 10 11 12 | import model.Book; import service.NaverBookService; public class App { public static void main(String[] args) { NaverBookService service = new NaverBookService(); for(Book b : service.searchBook("java", 20, 1)) System.out.println(b); } } | cs |
'Programming > JAVA' 카테고리의 다른 글
Java Stream API 사용해보기 (407) | 2021.05.25 |
---|---|
Java NIO ByteBuffer 사용해보기 (0) | 2021.04.22 |
Immutable Object(불변 객체) (405) | 2021.04.06 |
String, StringBuffer, StringBuilder의 차이점이 뭘까? (0) | 2020.08.07 |
[JAVA] TCP 1:1 채팅 (0) | 2016.04.18 |
댓글