woniper

naver 검색 API 예제 본문

Java

naver 검색 API 예제

Woniper 2017.01.10 20:09

  책 검색 서비스를 만들기 위해서 책 검색 API를 찾던 중 네이버 검색 API를 발견했다.

검색 API는 여러 종류에 검색 API를 제공하고 그 중 책 검색 API를 예제로 설명할 것이다. 사실 URL만 다르지 검색 API 모두 xml, json 구조는 모두 동일하고 아래와 같다.



XML : 기본 검색

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
    <channel>
        <title>Naver Open API - book ::'주식'</title>
        <link>http://search.naver.com</link>
        <description>Naver Search Result</description>
        <lastBuildDate>Mon, 26 Sep 2016 10:40:35 +0900</lastBuildDate>
        <total>20177</total><start>1</start><display>10</display>
        <item>
            <title>불곰의 <b>주식</b>투자 불패공식 (60개 매도종목 평균 수익률 62%)</title>
            <link>http://openapi.naver.com/l?AAAC3LSwqDMBSF4dXcDCV6YxsHGfiog6JIV1A0SYloGpumQnffFIQz+DnwvT7afwVcaigRqvofvIKiIcbrhzAhbIAlZG3c5NySPMdd+0Q6exxqOuKudBjnNdlMFO00K8AmpRzZKackiJSdGc8ZxZzSglix3vqhG6KVKPcis0vXX+k+vqXM2BLpDzHjEYWYAAAA</link>
            <image>http://bookthumb.phinf.naver.net/cover/108/346/10834650.jpg?type=m1&udate=20160902</image>
            <author>불곰 박선목</author>
            <price>16000</price>
            <discount>14400</discount>
            <publisher>부키</publisher>
            <pubdate>20160729</pubdate>
            <isbn>8960515523 9788960515529</isbn>
            <description>잘못된 <b>주식</b>투자 습관을 버리고, 절대로 지지 않는 투자법을 체득하다! </description>
        </item>
        ...
    </channel>
</rss>
cs


JSON : 상세 검색

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
    "lastBuildDate""Tue, 10 Jan 2017 19:44:39 +0900",
    "total"6374,
    "start"1,
    "display"5,
    "items": [
    {
        "title""<b>Java</b>의 정석 (최신 <b>Java</b> 8.0 포함)",
        "link""http://book.naver.com/bookdb/book_detail.php?bid=10191151",
        "image""http://bookthumb.phinf.naver.net/cover/101/911/10191151.jpg?type=m1&udate=20161124",
        "author""남궁성",
        "price""30000",
        "discount""27000",
        "publisher""도우출판",
        "pubdate""20160127",
        "isbn""8994492038 9788994492032",
        "description""자바의 기초부터 실전활용까지 모두 담다!자바의 기초부터 객제지향개념을 넘어 실전활용까지 수록한"
    }
}
cs


API 문서 자체는 설명하지 않겠다. 여기를 참고 하자.


Object

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
public class NaverBook {
 
    private String lastBuildDate;
    private int total;
    private int start;
    private int display;
    private List<Item> items;
 
    // getter and setter
 
    @Override
    public String toString() {
        return "NaverBook{" +
                "lastBuildDate='" + lastBuildDate + '\'' +
                ", total=" + total +
                ", start=" + start +
                ", display=" + display +
                '}';
    }
 
    public static class Item {
        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;
 
        // getter and setter
 
        @Override
        public String toString() {
            return "Item{" +
                    "title='" + title + '\'' +
                    ", link='" + link + '\'' +
                    ", image='" + image + '\'' +
                    ", author='" + author + '\'' +
                    ", price='" + price + '\'' +
                    ", discount='" + discount + '\'' +
                    ", publisher='" + publisher + '\'' +
                    ", pubdate='" + pubdate + '\'' +
                    ", isbn='" + isbn + '\'' +
                    ", description='" + description + '\'' +
                    '}';
        }
    }
}
cs


TEST

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
public class SearchApiTest {
    private static final String CLIENT_ID = "input your client_id";
    private static final String CLIENT_SECRET = "input your client_secret";
    private static final String URL = "https://openapi.naver.com/v1/search/book_adv.json";
 
    private HttpEntity<?> headers;
    private RestTemplate template = new RestTemplate();
 
    @Before
    public void setUp() throws Exception {
        MultiValueMap<StringString> headerMap = new LinkedMultiValueMap<>();
        headerMap.add("X-Naver-Client-Id", CLIENT_ID);
        headerMap.add("X-Naver-Client-Secret", CLIENT_SECRET);
        headerMap.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        this.headers = new HttpEntity<>(headerMap);
    }
 
    @Test
    public void requestString() throws Exception {
        String url = URL + "?d_titl=java&display=5";
        ResponseEntity<String> responseEntity = template.exchange(url, HttpMethod.GET, headers, String.class);
        assertThat(responseEntity).isNotNull();
 
        String body = responseEntity.getBody();
        assertThat(body).isNotNull();
    }
 
    @Test
    public void requestJson() throws Exception {
        String url = URL + "?d_titl=java&display=5";
        ResponseEntity<NaverBook> responseEntity = template.exchange(url, HttpMethod.GET, headers, NaverBook.class);
        assertThat(responseEntity).isNotNull();
 
        NaverBook body = responseEntity.getBody();
        assertThat(body).isNotNull();
        assertThat(body.getDisplay()).isNotNull();
        assertThat(body.getDisplay()).isEqualTo(5);
        assertThat(body.getLastBuildDate()).isNotNull();
        assertThat(body.getStart()).isNotNull();
        assertThat(body.getTotal()).isNotNull();
        assertThat(body.getItems()).isNotNull().isNotEmpty();
        assertThat(body.getItems().size()).isEqualTo(5);
    }
}
cs

Spring RestTemplate을 사용한 예제다.

0 Comments
댓글쓰기 폼