Suldo
Foundation of me
Suldo
전체 방문자
오늘
어제
  • 분류 전체보기 (33)
    • Back (18)
      • Spring (13)
      • node.js (2)
      • C# (3)
    • Front (1)
      • html (1)
      • css (0)
      • js (0)
      • react (0)
    • Sql (2)
    • 기초지식 (10)
      • 네트워크 (3)
      • DB 및 그 외 (7)
    • Error (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • RPC
  • node.js#node
  • 컨트롤러#Controller#spring
  • spring#aop#logging
  • spring#annotation#@Component
  • html#js
  • thymeleaf#jsp
  • spring#api
  • 직렬화#serializble
  • 삼항연산자
  • api#spring#aop

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Suldo

Foundation of me

[Java] 예제 네이버 파파고  api 이용해서 번역해보기
기초지식/DB 및 그 외

[Java] 예제 네이버 파파고 api 이용해서 번역해보기

2022. 8. 16. 17:05
728x90

본문에서는 간단하게 스프링이나 다른 프레임워크를 사용하거나 같이쓰지 않고 

자바 단독으로 application run 을이용하여 실습해보았습니다.


1. Naver 오픈 api 신청하기
https://developers.naver.com/apps/#/register?defaultScope=translate
위 주소에서 신청한다.

이름과 url은 상관없다. 본인은 localhost.com 입력
입력후 id와 pw 는 따로 적어놓도록 한다.

 

2. api 연동 코드 제작 - 네이버에 있는 예제소스를 그대로 붙여넣었습니다.
프로젝트와 클래스를 하나 만들어서 그대로 복사

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

// 네이버 기계번역 (Papago SMT) API 예제
public class ApiExamTranslateNmt {

    public static void main(String[] args) {
        String clientId = "여기가 아이디 ";//애플리케이션 클라이언트 아이디값";
        String clientSecret = "여기가 비밀번호";//애플리케이션 클라이언트 시크릿값";

        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);
        }
    }
}


실행시

이러한 화면 확인가능 translatedText에서 i'm a tiger butter fly 확인가능 (나는 호랑나비 입력시)

728x90
저작자표시 (새창열림)

'기초지식 > DB 및 그 외' 카테고리의 다른 글

Endian (엔디언) 이란?  (0) 2023.10.19
Jsp , thymeleaf / react , vue의 차이점  (0) 2022.09.02
JSP란?  (0) 2022.08.16
삼항연산자 in HTML  (0) 2022.08.16
직렬화 (serializble) 란?  (0) 2022.08.16
    '기초지식/DB 및 그 외' 카테고리의 다른 글
    • Endian (엔디언) 이란?
    • Jsp , thymeleaf / react , vue의 차이점
    • JSP란?
    • 삼항연산자 in HTML
    Suldo
    Suldo

    티스토리툴바