Preloader image
DDD

자바

네이버 한글인명-로마자변환 Open API 예제 - JSP로 구성

작성자 관리자 (admin)
조회수 293
입력일 2021-02-20 21:22:32

Windows DOS cmd
curl "https://openapi.naver.com/v1/krdict/romanization?query=%EC%9D%B4%EB%8C%80%EB%B2%94" -H "X-Naver-Client-Id: 7N5QRQ2qyBTsccN9JDea" -H "X-Naver-Client-Secret: 5iruByskUW" -v

-- HTML --
-- open_api_naver.html --​​​​​

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<pre>
    <form id="send_post">
        <input type="text"   name="dsp_type" value="0">
        <input type="text"   name="hname" value="이대범">
        <input type="button" id="send" value="#전송#">
    </form>
    <span id="result" style="border: solid red 1px;">결과</span>
</pre>

<script type="text/javascript">

//~ script start ~

// 유효성 검사
"use strict";

$(document).ready(function()
{
    console.log("페이지 시작~");

    //-- JSON to String 스크립트 예제 --
    var json_1 = { name: "Lee Digital", age : "30"};
    var json_str_1 = JSON.stringify( json_1 );
    console.log ( json_1 );
    console.log ( json_str_1 );

    //-- String to JSON 스크립트 예제 --
    var json_1 = '{ "name": "Lee Digital", "age" : "30"}';
    var str_1 = JSON.parse( json_1);
    console.log(  str_1 );
        
    // API Called
    $("#send").click(function()
    {
        var param = $("#send_post").serialize();
        console.log(param);
        
        $.ajax(
        {
              //url         : '/han_roma_api_process'
              url         : '/open_api_naver_roma_process.jsp'
            , type        : 'post'
            , data        : param
            , contentType : 'application/x-www-form-urlencoded; charset=UTF-8' 
            , dataType    : 'html'
            , success     : function (result)
            {
                console.log( result );
                $("#result").html(result);
            }
        });
    });
});

// ~ script end ~

</script>
</body>
</html>

-- JSP --
-- open_api_naver_roma_process.jsp --

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.io.BufferedInputStream" %>
<%@ page import="java.io.BufferedReader" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="java.io.UnsupportedEncodingException" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.MalformedURLException" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.nio.charset.Charset" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="org.json.JSONArray" %>
<%@ page import="org.json.JSONObject" %>
<%
String hname    = request.getParameter("hname");
String dsp_type = request.getParameter("dsp_type");
out.print(naver_han_roma(hname, dsp_type));
%>
<%!
/**
 * 
 * @param called_name
 * @return
 * @throws Exception 
 */
public String naver_han_roma(String called_name, String dsp_type) throws Exception
{
    String clientId     = "7N5QRQ2qyBTsccN9JDea"; // 애플리케이션 클라이언트 아이디값";
    String clientSecret = "5iruByskUW"          ; // 애플리케이션 클라이언트 시크릿값";
    String result = "";

    String text = null;
    try {
        text = URLEncoder.encode(called_name, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("검색어 인코딩 실패",e);
    }
    String apiURL = "https://openapi.naver.com/v1/krdict/romanization?query="+ text;

    Map<String, String> requestHeaders = new HashMap<>();
    requestHeaders.put("X-Naver-Client-Id", clientId);
    requestHeaders.put("X-Naver-Client-Secret", clientSecret);
    String responseBody = get(apiURL,requestHeaders);
    System.out.println( "==>> " + responseBody);

    if( "errorMessage".contentEquals(responseBody))
    result = responseBody; // 1 : 단일출력, 0 : 전체 출력        
    else
    result = display_roma( responseBody,"aResult","sFirstName","aItems","name", dsp_type ); // 1 : 단일출력, 0 : 전체 출력

    return result;
}

/**
 * json 3차배열 parser
 * @param json_data
 * @param div_txt_1
 * @param dsp_nm_1
 * @param div_txt_2
 * @param dsp_nm_2
 * @param flag
 * @return
 * @throws Exception
 */
public static String display_roma( String json_data, String div_txt_1, String dsp_nm_1, String div_txt_2, String dsp_nm_2, String flag ) throws Exception 
{
    // JSONObjet : key-value
    JSONObject jObject = new JSONObject(json_data);       // json 전체 데이터
    JSONArray   jArray = jObject.getJSONArray(div_txt_1); // 1번째 분할
    String sFirstName;
    String divide = "\n";
    String result = "";

    // div_txt_1 기준으로 배열 출력
    for (int i = 0; i < jArray.length(); i++)
    {
        JSONObject obj = jArray.getJSONObject(i);
        sFirstName = obj.getString(dsp_nm_1);

        // div_txt_2 기준으로 배열 출력 sub json array
        JSONArray subArray = obj.getJSONArray(div_txt_2);
        System.out.println( "json : " + subArray.toString().replaceAll("]","").replace("[","") );

        for (int j = 0; j < subArray.length(); j++)
        {
            if( "1".equals(flag) ) divide = "";

            if( j == 0 ) result += divide;

            result += subArray.getJSONObject(j).getString(dsp_nm_2) + divide;
            //System.out.println("name(" + j + "): " + subArray.getJSONObject(j).getString(dsp_nm_2)); // debug

            if( "1".equals(flag) ) break;
            else                   continue;
        }
    }
    // 결과값 파싱
    return result.replaceAll("\n","").replaceAll("]","").replace("[","");
}

/**
 * 
 * @param apiUrl
 * @param requestHeaders
 * @return
 */
public static String get(String apiUrl, Map<String, String> requestHeaders){
    HttpURLConnection con = connect(apiUrl);
    try {
        con.setRequestMethod("GET");
        for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
            con.setRequestProperty(header.getKey(), header.getValue());
        }

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
            return readBody(con.getInputStream());
            //return con.getInputStream().toString();               
        } else { // 에러 발생
            return readBody(con.getErrorStream());
        }
    } catch (IOException e) {
        throw new RuntimeException("API 요청과 응답 실패", e);
    } finally {
        con.disconnect();
    }
}

/**
 * 
 * @param apiUrl
 * @return
 */
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);
    }
}

/**
 * 
 * @param body
 * @return
 */
private static String readBody(InputStream body)
{
    InputStreamReader streamReader = new InputStreamReader(body);

    try (BufferedReader lineReader = new BufferedReader(streamReader)) {
        StringBuilder responseBody = new StringBuilder();

        String line;
        int count = 0;
        while ((line = lineReader.readLine()) != null) {
            if( count > 0) break;
            responseBody.append(line);
            System.out.println("line : " + line);
            count++;
        }

        return responseBody.toString();
    } catch (IOException e) {
        throw new RuntimeException("API 응답을 읽는데 실패했습니다.", e);
    }
}
%>

^