파파고 코드 수정
더보기
import java.io.BufferedReader;
import java.io.DataOutputStream;
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;
public class NaverAPI {
public static void translateKorToEng(String msg) {
String clientId = "RYMXbMmrZLRdCw3G53SG";//애플리케이션 클라이언트 아이디값";
String clientSecret = "lCfHkQotTh";//애플리케이션 클라이언트 시크릿값";
String apiURL = "https://openapi.naver.com/v1/papago/n2mt";
String text;
try {
text = URLEncoder.encode(msg, "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);
}
}
}
import java.util.Scanner;
//PAPAGO
public class Exam_01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("영어로 번역할 한글 입력 : ");
String msg = sc.nextLine();
NaverAPI.translateKorToEng(msg);
}
}
콘솔창
영어로 번역할 한글 입력 : 점심시간 2시간 30분 남았다.
{"message":{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"ko","tarLangType":"en","translatedText":"Two and a half hours left for lunch.","engineType":"N2MT","pivot":null}}}
자바스크립트 오브젝트 노테이션 :자바스크립트 객체
JSON
{키:밸류 키:밸류}
1) 정규표현식으로 원하는 데이터 뽑아낼 수도 있음
2) JSON 분석 라이브러리
- 가장 많이 쓰는 라이브러리 JsonSimple : 하지만 한계가 있음
- 구글에서 제공하는 Json 분석 라이브러리 - Gson
https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.6
Maven Repository: com.google.code.gson » gson » 2.8.6
com.google.code.gson gson 2.8.6 // https://mvnrepository.com/artifact/com.google.code.gson/gson compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6' // https://mvnrepository.com/artifact/com.google.code.gson/gson libraryDependencies += "co
mvnrepository.com
System.out.println(responseBody);
메세지를 키값으로 하는 값이 또 오브젝트 (3중)
{"message":
{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":
{"srcLangType":"ko","tarLangType":"en","translatedText":"Two and a half hours left for lunch.","engineType":"N2MT","pivot":null}}}
JsonElement root = JsonParser.parseString(responseBody);
JsonObject rootObj = root.getAsJsonObject();
rootObj.getAsJsonObject(memberName)
JsonElement : 오브젝트인지, 배열인지 스트링인지, ... 알지못함 - 처음 가져온 프로토타입 (getAsJsonObject 없음)
JsonObject : 오브젝트 타입을 쓰기위해 치환 (getAsJsonObject 존재)
JsonObject messageObj = rootObj.getAsJsonObject("message");
message 키값에 대한 밸류값 꺼내기
{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":
{"srcLangType":"ko","tarLangType":"en","translatedText":"Two and a half hours left for lunch.","engineType":"N2MT","pivot":null}}
JsonElement root = JsonParser.parseString(responseBody);
JsonObject rootObj = root.getAsJsonObject();
JsonObject messageObj = rootObj.getAsJsonObject("message");
messageObj resultObj = messageObj.getAsJsonObject("result");
//translatedText의 밸류값은 오브젝트가 아닌 스트링
String message = resultObj.get("translatedText").getAsString();
//콘솔창
영어로 번역할 한글 입력 : 안녕
{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"ko","tarLangType":"en","translatedText":"Hi.","engineType":"N2MT","pivot":null}}
{"srcLangType":"ko","tarLangType":"en","translatedText":"Hi.","engineType":"N2MT","pivot":null}
Hi.
더보기
import java.io.BufferedReader;
import java.io.DataOutputStream;
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.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class NaverAPI {
public static void translateKorToEng(String msg) {
String clientId = "RYMXbMmrZLRdCw3G53SG";//애플리케이션 클라이언트 아이디값";
String clientSecret = "lCfHkQotTh";//애플리케이션 클라이언트 시크릿값";
String apiURL = "https://openapi.naver.com/v1/papago/n2mt";
String text;
try {
text = URLEncoder.encode(msg, "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);
//뿌리데이터
JsonElement root = JsonParser.parseString(responseBody);
JsonObject rootObj = root.getAsJsonObject();
JsonObject messageObj = rootObj.getAsJsonObject("message");
System.out.println(messageObj);
//{"@type":"response","@service":"naverservice.nmt.proxy","@version":"1.0.0","result":{"srcLangType":"ko","tarLangType":"en","translatedText":"Hi.","engineType":"N2MT","pivot":null}}
JsonObject resultObj = messageObj.getAsJsonObject("result");
System.out.println(resultObj);
//{"srcLangType":"ko","tarLangType":"en","translatedText":"Hi.","engineType":"N2MT","pivot":null}
String message = resultObj.get("translatedText").getAsString();
System.out.println(message);
}
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);
}
}
}
import java.util.Scanner;
//PAPAGO
public class Exam_01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("영어로 번역할 한글 입력 : ");
String msg = sc.nextLine();
NaverAPI.translateKorToEng(msg);
}
}
'디지털 컨버전스 > OpenApi' 카테고리의 다른 글
| [이미지업로드] summernote (0) | 2020.05.25 |
|---|---|
| [WebAPI] 지도 (0) | 2020.04.23 |
| [WebAPI] 검색 API 추가 (0) | 2020.04.23 |
| [WebAPI] PAPAGO - 다른 언어 활용 (0) | 2020.04.23 |
| [WebAPI] PAPAGO (0) | 2020.04.23 |