개발자센터 API레퍼런스 / 구현예제 활용해보기

https://developers.naver.com/docs/papago/papago-nmt-api-reference.md

 

Papago 번역 API 레퍼런스 - Papago API

Papago 번역 API 레퍼런스 인공 신경망 기반 기계 번역 설명 인공 신경망 기반의 기계 번역(NMT, Neural Machine Translation) 결과를 반환합니다. 요청 URL https://openapi.naver.com/v1/papago/n2mt 프로토콜 HTTPS HTTP 메서드 POST 파라미터 파라미터 타입 필수 여부 설명 source String Y 원본 언어(source language)의 언어 코드 target String Y

developers.naver.com

 

타켓 언어 변경

예외처리

더보기
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)throws Exception {
		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)throws Exception{
		HttpURLConnection con = connect(apiUrl);
		//타켓 언어 변격
		String postParams = "source=ko&target=ru&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) throws Exception{
		InputStreamReader streamReader = new InputStreamReader(body, "UTF-8");

		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();
		try {
		NaverAPI.translateKorToEng(msg);
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("번역에 실패했습니다.");
		}
	}
}

 

'디지털 컨버전스 > OpenApi' 카테고리의 다른 글

[이미지업로드] summernote  (0) 2020.05.25
[WebAPI] 지도  (0) 2020.04.23
[WebAPI] 검색 API 추가  (0) 2020.04.23
[WebAPI] GSON  (0) 2020.04.23
[WebAPI] PAPAGO  (0) 2020.04.23

+ Recent posts