Commit f28753a2 authored by Deokhyun Lee's avatar Deokhyun Lee

APIHandler created and added to main

parent ae5a3f9a
package dto;
public class NaverApiDTO {
// 제목
private String title;
// 링크
private String link;
// 날짜
private String pubDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
}
package member;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import dto.NaverApiDTO;
import java.util.Scanner;
import java.util.Scanner;
public class APIHandler {
NaverAPI nv;
Gson gson;
Scanner sc = new Scanner(System.in);
String responseBody = null;
String keyword = null;
int counter = 0;
public APIHandler() {
nv = new NaverAPI();
gson = new Gson();
System.out.println("1. 뉴스 검색; 2. 블로그 검색; 3. 영화 검색; 4. 책 검색");
counter = Integer.parseInt(sc.nextLine());
System.out.print("Keyword를 말해주세요");
keyword = sc.nextLine();
if (counter == 1){
responseBody = nv.searchNews(keyword);
}else if (counter == 2){
responseBody = nv.searchBlog(keyword);
}
JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("items");
for (JsonElement em : jsonArray) {
NaverApiDTO dto = gson.fromJson(em, NaverApiDTO.class);
System.out.println(dto.getTitle());
System.out.println(dto.getLink());
System.out.println(dto.getPubDate());
}
}
}
......@@ -48,8 +48,10 @@ public class MainClass {
changedPassword = sc.nextLine();
memberDao.updateUserInfo(email, password, changedPassword);
}
if (memberDao.isApproved()){
if (memberDao.isApproved()) {
System.out.println("접속 성공!");
//여기서
APIHandler apiHandler = new APIHandler();
}
}
......
package member;
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;
import com.ldk.util.Util;
public class NaverAPI {
String clientId = APICode.ID;
String clientSecret = APICode.PWD;
public String searchNews(String str) {
String apiURL = "https://openapi.naver.com/v1/search/news?query=" + str; // json 결과
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);
return responseBody;
}
public String searchBlog(String str) {
String apiURL = "https://openapi.naver.com/v1/search/blog?query=" + str; // json 결과
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);
return responseBody;
}
public 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();
}
}
public 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);
}
}
public String readBody(InputStream body) {
InputStreamReader streamReader = new InputStreamReader(body);
try (BufferedReader lineReader = new BufferedReader(streamReader)) {
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
responseBody.append(line);
}
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment