반응형
# Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출 후 Excel에 저장하기
- Naver Search API 연동, 도서정보를 입력(요청 변수 값) 하여 원하는 정보(ISBN, IMAGE) 검출. (Jsoup 사용)
- 검출된 데이터 Excel에 저장.
## 작업 소스
- 메인 java 소스
import java.io.*;
import kr.inflearn.ExcelDAO;
public class Project03_F {
public static void main(String[] args) {
ExcelDAO dao = new ExcelDAO();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("입력처리(I) / 종료(E) : ");
String sw = br.readLine();
switch (sw) {
case "I":
dao.excel_input();
break;
case "E":
System.out.println("프로그램이 종료됩니다.");
System.exit(0);
break;
default:
System.out.println("I or E 를 입력해주세요.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 실 기능 수행하는 java 소스
package kr.inflearn;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class ExcelDAO {
private List<ExcelVO> list;
private HSSFWorkbook wb;
public ExcelDAO() {
list = new ArrayList<ExcelVO>();
wb = new HSSFWorkbook();
}
public void excel_input() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
HSSFSheet firstSheet = wb.createSheet("BOOK SHEET");
HSSFRow rowA = firstSheet.createRow(0);
HSSFCell cellA = rowA.createCell(0);
cellA.setCellValue(new HSSFRichTextString("책제목"));
HSSFCell cellB = rowA.createCell(1);
cellB.setCellValue(new HSSFRichTextString("저자"));
HSSFCell cellC = rowA.createCell(2);
cellC.setCellValue(new HSSFRichTextString("출판사"));
HSSFCell cellD = rowA.createCell(3);
cellD.setCellValue(new HSSFRichTextString("ISBN"));
HSSFCell cellE = rowA.createCell(4);
cellE.setCellValue(new HSSFRichTextString("이미지이름"));
int i = 1;
while (true) {
System.out.print("책의 제목을 입력해주세요 : ");
String title = br.readLine();
System.out.print("책의 저자를 입력해주세요 : ");
String author = br.readLine();
System.out.print("책의 출판사를 입력해주세요 : ");
String company = br.readLine();
HSSFRow rowRa1 = firstSheet.createRow(i);
HSSFCell cellTitle = rowRa1.createCell(0);
cellTitle.setCellValue(new HSSFRichTextString(title));
HSSFCell cellAuthor = rowRa1.createCell(1);
cellTitle.setCellValue(new HSSFRichTextString(author));
HSSFCell cellCompany = rowRa1.createCell(2);
cellTitle.setCellValue(new HSSFRichTextString(company));
i++;
ExcelVO vo = new ExcelVO(title, author, company);
ExcelVO data = naver_search(vo);
list.add(data);
System.out.println("계속 입력하시려면 Y / 종료하시려면 N 을 입력해주세요 : ");
String key = br.readLine();
if (key.equals("N")) break;
}
System.out.println("데이터 추출 작업 중 입니다.........");
excel_save();
} catch (Exception e) {
e.printStackTrace();
}
}
private ExcelVO naver_search(ExcelVO vo) {
try {
String openApi = "https://openapi.naver.com/v1/search/book_adv.xml?d_titl="
+ URLEncoder.encode(vo.getTitle(), "UTF-8")
+ "&d_auth=" + URLEncoder.encode(vo.getAuthor(), "UTF-8")
+ "&d_publ="+ URLEncoder.encode(vo.getCompany(), "UTF-8");
URL url = new URL(openApi);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-Naver-Client-Id", "발급받은 Client_Id 입력");
con.setRequestProperty("X-Naver-Client-Secret", "발급받은 Client_Secret 입력");
int responseCode = con.getResponseCode();
BufferedReader br1 = null;
if (responseCode == 200) {
br1 = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
} else {
br1 = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine = null;
StringBuffer response = new StringBuffer();
while ((inputLine = br1.readLine()) != null) {
response.append(inputLine);
}
br1.close();
// ISBN, IMAGE 정보 꺼내기
Document doc = Jsoup.parse(response.toString());
Element isbn = doc.select("isbn").first();
String img = doc.toString();
String imgTag = img.substring(img.indexOf("<img>")+5);
img = imgTag.substring(0, imgTag.indexOf("?"));
vo.setIsbn(isbn.text().split(" ")[1]);
String fileName = img.substring(img.lastIndexOf("/")+1);
vo.setImageUrl(fileName);
// DownloadBroker
Runnable download = new DownloadBroker(img, fileName);
Thread t = new Thread(download);
t.start();
} catch (Exception e) {
e.printStackTrace();
}
return vo;
}
private void excel_save() {
try {
HSSFSheet sheet = wb.getSheetAt(0);
if (wb != null && sheet != null) {
Iterator rows = sheet.rowIterator();
rows.next();
int i = 0;
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
HSSFCell cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue(list.get(i).getIsbn());
cell = row.createCell(4);
cell.setCellType(CellType.STRING);
cell.setCellValue(list.get(i).getImageUrl());
InputStream inputStream = new FileInputStream(list.get(i).getImageUrl());
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
inputStream.close();
CreationHelper helper = wb.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(5);
anchor.setRow1(i+1);
anchor.setCol2(6);
anchor.setRow2(i+2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
Cell cellImg = row.createCell(5);
int widthUnits = 20*256;
sheet.setColumnWidth(5, widthUnits);
short heightUnits = 120*20;
cellImg.getRow().setHeight(heightUnits);
i++;
}
FileOutputStream fos = new FileOutputStream("isbn.xls");
wb.write(fos);
fos.close();
System.out.println("ISBN 및 ImageURL 저장 성공.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
## 출력 결과
- 아래와 같이 진행 시 Java의 정석 책 표지 이미지가 추출되어 저장되는것을 확인할 수 있다.
반응형
'인프런 강의 학습 > Java TPC 실전' 카테고리의 다른 글
Java iText API 활용 PDF 에 Paragraph(단락, 문단, 절) 만들기 (0) | 2022.07.27 |
---|---|
Java iText API 활용 PDF table 만들기 (0) | 2022.07.25 |
Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출하기 (0) | 2022.07.20 |
Naver Search API 활용 Excel에서 Cell의 데이터타입 알아보기 (0) | 2022.07.11 |
API활용_Naver Search API 활용 Excel에 image 저장하기 (0) | 2022.07.11 |