본문 바로가기
프로그래밍/Kotlin

[Kotlin] Naver API를 이용해 책 검색 코드

by Youngs_ 2022. 7. 20.
fun bookSearch(searchWord : String) : JSONObject{

	// 클라이언트 ID와 Secret은 네이버 API를 등록할때 생성된 값을 넣는다.
    
        val clientId = "클라이언트 ID"
        val clientSecret = "클라이언트 Secret"
        
        var bookJsonObject : JSONObject = JSONObject()

        try {
                CoroutineScope(Dispatchers.IO).launch {
                    val text: String = URLEncoder.encode(searchWord, "UTF-8")
                    val apiURL =
                        "https://openapi.naver.com/v1/search/book.json" + "?query=" + text + "&display=20" // json 결과
                    //String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // xml 결과
                    val url = URL(apiURL)
                    val con: HttpURLConnection = url.openConnection() as HttpURLConnection
                    con.setRequestMethod("GET")
                    con.setRequestProperty("X-Naver-Client-Id", clientId)
                    con.setRequestProperty("X-Naver-Client-Secret", clientSecret)
                    Log.d("네이버 url", apiURL)
                    Log.d("con.responseCode", con.responseCode.toString())
                    val responseCode: Int = con.getResponseCode()
                    val br: BufferedReader
                    if (responseCode == 200) { // 정상 호출
                        br = BufferedReader(InputStreamReader(con.getInputStream(), "UTF-8"))
                    } else {  // 에러 발생
                        br = BufferedReader(InputStreamReader(con.getErrorStream()))
                    }
                    var inputLine: String?
                    val response = StringBuffer()
                    while (br.readLine().also { inputLine = it } != null) {
                        response.append(inputLine)
                        response.append("\n")
                    }
                    br.close()
                    val naverHtml: String = response.toString()
                    val bun = Bundle()
                    bun.putString("NAVER_HTML", naverHtml)


                    bookJsonObject = JSONObject(response.toString())

            }.join()
            } catch (e: Exception) {
            e.printStackTrace()
        }
        return bookJsonObject
    }

댓글