https://developers.naver.com/main/
NAVER Developers
네이버 오픈 API들을 활용해 개발자들이 다양한 애플리케이션을 개발할 수 있도록 API 가이드와 SDK를 제공합니다. 제공중인 오픈 API에는 네이버 로그인, 검색, 단축URL, 캡차를 비롯 기계번역, 음성인식, 음성합성 등이 있습니다.
developers.naver.com
public static void main(String[] args) {
String clientId = "YOUR_CLIENT_ID";//애플리케이션 클라이언트 아이디값";
String clientSecret = "YOUR_CLIENT_SECRET";//애플리케이션 클라이언트 시크릿값";
String apiURL = "https://openapi.naver.com/v1/papago/n2mt";
String text;
try {
text = URLEncoder.encode("안녕하세요. 오늘 기분은 어떻습니까?", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("인코딩 실패", e);
}
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Naver-Client-Id", clientId);
requestHeaders.put("X-Naver-Client-Secret", clientSecret);
String responseBody = post(apiURL, requestHeaders, text);
System.out.println(responseBody);
}
private static String post(String apiUrl, Map<String, String> requestHeaders, String text){
HttpURLConnection con = connect(apiUrl);
String postParams = "source=ko&target=en&text=" + text; //원본언어: 한국어 (ko) -> 목적언어: 영어 (en)
try {
con.setRequestMethod("POST");
for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postParams.getBytes());
wr.flush();
}
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){
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);
}
}
도스공격을 막기위한 인증
String clientId = "YOUR_CLIENT_ID";//애플리케이션 클라이언트 아이디값";
String clientSecret = "YOUR_CLIENT_SECRET";//애플리케이션 클라이언트 시크릿값";
Request 를 보내주려고 하는 url
String apiURL = "https://openapi.naver.com/v1/papago/n2mt";
Client 측에서 Naver로 요청
Request (하나의 가방으로 생각해보기)
- 헤더 : SIP(샌더아이피) , DIP(데스티네이션아이피) , 브라우저 , Port번호, Data , 인코딩
- 바디영역 : 내용
Response
인코딩 : 텍스트가 깨지지 않도록함
String text;
try {
text = URLEncoder.encode("안녕하세요. 오늘 기분은 어떻습니까?", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("인코딩 실패", e);
}
헤더 영역에 들어갈 내용을 Map으로 만듦
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Naver-Client-Id", clientId);
requestHeaders.put("X-Naver-Client-Secret", clientSecret);
리퀘스트를 보내는 방식 (get방식 / post방식)
String responseBody = post(apiURL, requestHeaders, text);
private static String post(String apiUrl, Map<String, String> requestHeaders, String text){
HttpURLConnection con = connect(apiUrl);
String postParams = "source=ko&target=en&text=" + text; //원본언어: 한국어 (ko) -> 목적언어: 영어 (en)
try {
con.setRequestMethod("POST");
for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postParams.getBytes());
wr.flush();
}
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();
}
}
자바 내장, 네트워크 통신 연결
HttpURLConnection con = connect(apiUrl);
리퀘스트를 코드상으로 보내도록 해주는 기능 (검색창 버튼 누르지 않고 보내기)
인자값으로 받아서 보낼 데이터 세팅
con.setRequestMethod("POST");
for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
보내기
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postParams.getBytes());
wr.flush();
}
응답코드 확인
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 응답
return readBody(con.getInputStream());
} else { // 에러 응답
return readBody(con.getErrorStream());
}
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);
}
}
'디지털 컨버전스 > OpenApi' 카테고리의 다른 글
| [이미지업로드] summernote (0) | 2020.05.25 |
|---|---|
| [WebAPI] 지도 (0) | 2020.04.23 |
| [WebAPI] 검색 API 추가 (0) | 2020.04.23 |
| [WebAPI] PAPAGO - 다른 언어 활용 (0) | 2020.04.23 |
| [WebAPI] GSON (0) | 2020.04.23 |