@Controller
public class BookController extends HttpServlet {
/**
* @param req
* @param model
* @param rttr
* @return
* @throws IOException
*/
@RequestMapping(value = "/book", method = RequestMethod.POST)
public String postBookHome(HttpServletRequest req, Model model,
RedirectAttributes rttr) throws IOException {
// get ์ฑ
์ด๋ฆ
String sbName = req.getParameter("sbname");
// ํ๊ธ ์ธ์ฝ๋ฉ | url ์์ด๋ ๋ฐ๋ก ์ ์ฉ๋์ง๋ง, ํ๊ธ์ ์ธ์ฝ๋ฉ์ด ํ์ํ๋ค.
String bookName = URLEncoder.encode(sbName, "UTF-8");
// 'REST API URL' + 'query' = ์ฑ
์ด๋ฆ
URL url = new URL("https://dapi.kakao.com/v3/search/book?query=" + bookName);
// Kakao dev rest api ๋ฐ๊ธ
String kakao_apikey = "{REST API Key}";
// Custom Serialize
ObjectMapper mapper = new ObjectMapper();
//
StringBuilder sb = new StringBuilder();
//
BufferedReader br;
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Request Header ์ ์
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "KakaoAK " + kakao_apikey);
// ์ ์ก๋ฐฉ์
con.setRequestMethod("GET");
// ์๋ฒ์ ์ฐ๊ฒฐ๋๋ Timeout ์๊ฐ ์ค์
con.setConnectTimeout(5000);
// InputStream ์ฝ์ด ์ค๋ Timeout ์๊ฐ ์ค์
con.setReadTimeout(5000);
// URLConnection์ ๋ํ doOutput ํ๋๊ฐ์ ์ง์ ๋ ๊ฐ์ผ๋ก ์ค์ ํ๋ค.
// URL ์ฐ๊ฒฐ์ ์
์ถ๋ ฅ์ ์ฌ์ฉ๋ ์ ์๋ค.
// URL ์ฐ๊ฒฐ์ ์ถ๋ ฅ์ฉ์ผ๋ก ์ฌ์ฉํ๋ ค๋ ๊ฒฝ์ฐ DoOutput ํ๋๊ทธ๋ฅผ true๋ก ์ค์ ํ๊ณ ,
// ๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ๋ false๋ก ์ค์ ํด์ผ ํ๋ค. ๊ธฐ๋ณธ๊ฐ์ false์ด๋ค.
con.setDoOutput(true);
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
// json ํํ๋ก ๋ง๋ค๊ธฐ
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
BookInfoVO sbList = mapper.readValue(sb.toString(), BookInfoVO.class);
rttr.addFlashAttribute("listMap", sbList); // "listMap" Parameter ์ ๋ฌ
} else {
model.addAttribute("error", con.getResponseMessage());
}
} catch (Exception e) {
System.err.println(e.toString());
}
return "redirect:/book"; // Parameter ์ ๋ฌ ๊ฒฝ๋ก
}
}