ysk(0soo)
Lifealong
ysk(0soo)
전체 방문자
오늘
어제
  • 분류 전체보기 (238)
    • Java (50)
      • whiteship-java-study (11)
      • Java (28)
      • time (6)
    • Spring (68)
      • JPA (15)
      • Spring (1)
      • SpringBoot (1)
      • SpringMVC (6)
      • Spring Security (22)
      • Jdbc (1)
      • RestDocs (14)
      • log (6)
    • Kotlin (3)
    • Web (2)
      • nginx (1)
    • Database (14)
      • MySQL (5)
      • PostgreSQL (1)
      • SQL (1)
      • Redis (4)
    • C, C++ (0)
    • Git (1)
    • Docker (2)
    • Cloud (3)
      • AWS (3)
    • 도서, 강의 (0)
      • t5 (0)
    • 기타 (7)
      • 프로그래밍 (1)
    • 끄적끄적 (0)
    • CS (14)
      • 운영체제(OS) (2)
      • 자료구조(Data Structure) (9)
    • 하루한개 (12)
      • 우아한 테크코스-10분테코톡 (12)
    • 스터디 (12)
      • 클린 아키텍처- 로버트마틴 (2)
      • JPA 프로그래밍 스터디 (10)
    • 테스트 (34)
      • JUnit (19)
      • nGrinder (2)
      • JMeter (0)
    • Infra (3)
    • 프로그래머스 백엔드 데브코스 3기 (0)
    • 디자인 패턴 (3)
    • Issue (4)
    • system (1)
      • grafana (0)
      • Prometheus (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

공지사항

인기 글

태그

  • node exporter basic auth
  • FilterSecurityInterceptor
  • java
  • jpa
  • 가상 스레드
  • UserDetailsService
  • junit5
  • 동일성
  • AuthenticationException
  • scope value
  • 트랜잭션
  • restdocs enum
  • AccessDecisionManager
  • DataJpaTest
  • 정규표현식
  • querydsl
  • nGrinder
  • restdocs custom
  • 동등성
  • AccessDecisionVoter 커스텀
  • tree
  • nginx basic auth
  • 가상 스레드 예외 핸들링
  • StructuredConcorrency
  • VirtualThread Springboot
  • 구조화된 동시성
  • 인가(Authorization) 처리
  • mysql
  • 동시성 제어
  • LocalDateTime

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ysk(0soo)

Lifealong

Java Papago 번역 API 사용
Java/Java

Java Papago 번역 API 사용

2023. 1. 26. 20:48
  • 파파고 번역 개요
  • API 문서 (API 레퍼런스)
  • 구현 예제 - 공식문서(Java)

Java를 이용한 Papago API 호출 예제이다.

Papago 번역 API는 일 허용량이 10,000 글자이다.

 

  • 일일 호출양이 끝난 상태.

 

애플리케이션 등록

  • https://developers.naver.com/docs/papago/papago-nmt-overview.md#%EC%95%A0%ED%94%8C%EB%A6%AC%EC%BC%80%EC%9D%B4%EC%85%98-%EB%93%B1%EB%A1%9D
  1. 애플리케이션 등록
  • 네이버 개발자 센터 상단 Application -> 애플리케이션 등록 -> 애플리케이션 등록 (API 이용신청) 페이지
  • 애플리케이션 이름, 사용 API, 비로그인 오픈 API 서비스 환경 입력

   2. 애플리케이션 등록 확인

  • 네이버 개발자 센터 상단 Application -> 내 애플리케이션 -> 애플리케이션에 등록된 Papago 번역 애플리케이션 정보
  • Client ID / Client Secret 확인
    • API 요청 시 HTTP 요청 헤더에 필요.

Code

clientId, clientSecret 가 노출되지 않도록 properties 에 설정 하는 등 코드에 노출되지 않도록 한 후 사용해야 한다.

  • ObjectMapper를 통해서 String 이 아닌 Object 상태로 리턴받을 수도 있다.

PapagoApiClient.java

public class PapagoApiClient {
  
  private final PapagoProperties properties;
​
  private final ObjectMapper mapper;
  
  public String translate(String text) {
    
    Map<String, String> requestHeaders = new HashMap<>();
    requestHeaders.put("X-Naver-Client-Id", properties.getClientId());
    requestHeaders.put("X-Naver-Client-Secret", properties.getClientSecret());
    
    String response = post(properties.getUrl(), requestHeaders, encodeText(text, "UTF-8"));
    
    ApiResponse apiResponse = mapper.readValue(response, ApiResponse.class);
    
    return apiResponse.getTransaltedText();
  }
  
  private String encodeText(String text, String charset) {
    try {
      return URLEncoder.encode(text, charset);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("인코딩 실패", e);
    }
  }
  
  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);
    }
  }
  
}

PapagoProperties

@Getter
@ConstructorBinding
@ConfigurationProperties(prefix = "translator.papago")
public class PapagoProperties {
​
  private String url;
  
  private String clientId;
​
  private String clientSecret;
}

ApiResponse

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse {
​
  private Message message;
​
  public String getTranslatedText() {
    return getMessage().getResult().getTranslatedText();
  }
  @Getter
  @JsonIgnoreProperties(ignoreUnknown = true)
  private static class Message {
      private Result result;
  }
​
  @Getter
  @JsonIgnoreProperties(ignoreUnknown = true)
  private static class Result {
      private String srcLangType;
      private String tarLangType;
      private String translatedText;
      private String engineType;
      private String pivot;
      private String dict;
      private String tarDict;
  }
}

@JsonIgnoreProperties

  • 무시할 속성이나 속성 목록을 표시하는 데 사용

구글 번역 API 는 월 500,000자 까지 사용이 가능하지만, 이후에는 백만 자당 $20가 부과된다.

저작자표시 비영리 (새창열림)

'Java > Java' 카테고리의 다른 글

Java Future, Callable, Executor Concurrent 프로그래밍  (0) 2023.04.23
Java 현재 시간 + 랜덤 문자로 고유값 만들기 - with apache commons library (Java Random String)  (0) 2023.01.28
Graceful Shutdown - JVM, Java, SpringBoot  (4) 2023.01.06
Lambda 표현식  (0) 2023.01.04
Java Annotation  (0) 2023.01.03
    'Java/Java' 카테고리의 다른 글
    • Java Future, Callable, Executor Concurrent 프로그래밍
    • Java 현재 시간 + 랜덤 문자로 고유값 만들기 - with apache commons library (Java Random String)
    • Graceful Shutdown - JVM, Java, SpringBoot
    • Lambda 표현식
    ysk(0soo)
    ysk(0soo)
    백엔드 개발을 좋아합니다. java kotlin spring, infra 에 관심이 많습니다. email : kim206gh@naver.com github : https://github.com/devysk

    티스토리툴바