네이버 도서 API활용

script

<script>   
   //NaverOpenApi사용하기
   $(function(){
	   $('#openBtn').click(function(){
		   var keyword=$('#books').val();
		   if(!keyword){
			   alert('검색어를 입력하세요');
			   $('#book').focus();
			   return;
		   }
		   var url="naverOpenApiResult.jsp?query="+encodeURIComponent(keyword);
		   send(url,keyword);
	   })
   })
   
   var send=function(url,keyword){
	   $.ajax({
		   type:'get',
		   url:url,
		   dataType:'json',
		   cache:false,
		   success:function(res){
			   //alert(JSON.stringify(res));
			   //alert(res.total)
			   var total=parseInt(res.total);
			   showDataList(res.items, total);
			   var display=20;
			   showPageList(total,keyword,display);
		   },
		   error:function(err){
			   alert('error: '+err.status);
		   }
	   })
   }
   var showDataList=function(items, total){
	   var str="<h2>"+$('#books').val()+" 검색 결과 " +total+"개</h2>";
	   str+="<table class='table'>"
	   str+="<tr>";

	   $.each(items,function(i,book){
		   str+="<td width='25%'>";
		   str+="<a href='"+book.link+"' target='_blank'>";
		   str+="<img src='"+book.image+"' class='img-fluid'>";
		   str+="</a>";
		   str+="<h4>"+book.title+"</h4>";
		   str+="<p>저자: "+book.author+"<br></p>";
		   str+="출판사: "+book.publisher+"<br>";
		   str+="정가: "+book.price+"원<br>";
		   str+="출판일: "+book.pubdate+"원<br>";
		   if(book.discount){
		   	str+="<span class='text-danger'> 할인가: "+book.discount+"원</span><br>";
		   }
		   str+="</td>";
		   if(i%4==3){
			   str+="</tr><tr>"
		   }
	   })
	   
	   str+="</tr>";
	   str+="</table>";
	   $('#localBook').hide(500);
	   $('#openApiBook').html(str).show(500);
   }//showdatalist() end -----------------------------
   
   var showPageList=function(total, keyword, display){
	   if(total>200){
		   total=200;
	   }
	   //int pageCount = (total-1)/display+1; <=자바에서 페이지수 구하기
	   var pageCount=Math.floor((total-1)/display+1);
	   
	   var str="<ul class='pagination justify-content-center'>";
	   /*
	   	i	start	display
	   [1]	1		20
	   [2]	21		20
	   [3]	41		20
	   
	   start = (i-1)*display+1;
	   */
	   
	   for(var i=1;i<=pageCount;i++){
		   var start =(i-1)*display+1;
		   str+="<li class='page-item' id='a"+start+"'><a class='page-link' onclick='show("+start+",\""+keyword+"\")'>"+i;
		   str+="</a></li>";
	   }
	   str+="</ul>";
	   $('#openApiBook').append(str);
   }
   var show=function(start,query){
	   //alert(start+"/"+query);
	   $('#a'+start).addClass('active');
   }
</script>

naverOpenApi.jsp

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="bookNaver" class="ajax.book.BookNaverProxy" scope="session"/>
<%
	String query=request.getParameter("query");
	if(query==null){
		query="Ajax";//기본 검색어
	}
	//시작 페이지
	String start=request.getParameter("start");
	if(start==null||start.trim().isEmpty()){
		start="1";//시작 페이지를 1페이지로 지정
	}
	String display="10"; //한 페이지당 보여줄 도서 갯수
	String sort="sim";//정렬방식 (sim또는 date)
	String data=bookNaver.getData(query,start,display,sort);
%>
<%=data%>

Proxy

package ajax.book;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class BookNaverProxy {
	public String getData(String keyword) {
		String clientId = ""; //애플리케이션 클라이언트 아이디값"
        String clientSecret = ""; //애플리케이션 클라이언트 시크릿값"

        String text = null;
        try {
            text = URLEncoder.encode(keyword, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("검색어 인코딩 실패",e);
        }
        System.out.println(text);
        String apiURL = "https://openapi.naver.com/v1/search/book.json?query=" + text;    // json 결과
        //String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과

        Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put("X-Naver-Client-Id", clientId);
        requestHeaders.put("X-Naver-Client-Secret", clientSecret);
        String responseBody = get(apiURL,requestHeaders);

        System.out.println(responseBody);
        return responseBody;
	}
	public String getData(String keyword,String start, String display, String sort) {
		String clientId = ""; //애플리케이션 클라이언트 아이디값"
        String clientSecret = ""; //애플리케이션 클라이언트 시크릿값"

        String text = null;
        try {
            text = URLEncoder.encode(keyword, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("검색어 인코딩 실패",e);
        }
        String queryStr="query="+text+"&start="+start+"&display="+display+"&sort="+sort;
        String apiURL = "https://openapi.naver.com/v1/search/book.json?"+queryStr;    // json 결과
        //String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과

        Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put("X-Naver-Client-Id", clientId);
        requestHeaders.put("X-Naver-Client-Secret", clientSecret);
        String responseBody = get(apiURL,requestHeaders);

        System.out.println(responseBody);
        return responseBody;
	}
	private static String get(String apiUrl, Map<String, String> requestHeaders){
        HttpURLConnection con = connect(apiUrl);
        try {
            con.setRequestMethod("GET");
            for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
                con.setRequestProperty(header.getKey(), header.getValue());
            }

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
                return readBody(con.getInputStream());
            } else { // 에러 발생
                return readBody(con.getErrorStream());
            }
        } catch (IOException e) {
            throw new RuntimeException("API 요청과 응답 실패", e);
        } finally {
            con.disconnect();
        }
    }
    private static HttpURLConnection connect(String apiUrl){
        try {
            URL url = new URL(apiUrl);
            return (HttpURLConnection)url.openConnection();
        } catch (MalformedURLException e) {
            throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
        } catch (IOException e) {
            throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
        }
    }

    private static String readBody(InputStream body){
        try {
	    	InputStreamReader streamReader = new InputStreamReader(body,"UTF-8");
	        BufferedReader lineReader = new BufferedReader(streamReader);
            StringBuilder responseBody = new StringBuilder();
            String line;
            while ((line = lineReader.readLine()) != null) {
                responseBody.append(line);
            }
            lineReader.close();
            streamReader.close();
            return responseBody.toString();
        } catch (IOException e) {
            throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e);
        }
    }
}


ConnectionPool에서 가져오기

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration  
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<typeAliases>
		<typeAlias type="shop.domain.ProductVO" alias="Product"/>
		<typeAlias type="shop.domain.CategoryVO" alias="Category"/>
	</typeAliases>
	<environments default="MyDBCP">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
				<property name="username" value="myshop" />
				<property name="password" value="tiger" />
			</dataSource>
		</environment>
		<environment id="MyDBCP">
			<transactionManager type="JDBC" />
			<dataSource type="JNDI">
				<property name="data_source" value="java:comp/env/jdbc/myshop" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="common/mapper/SampleMapper.xml" />
		<mapper resource="common/mapper/ProductMapper.xml" />
	</mappers>
</configuration>

+ Recent posts