[220,124]プロジェクト初日


NAVER CLOUD PLATFORMを使用したCATCHA API

Naver Capture APIの例


リリースキー

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test906 {
	public static void main(String[] args) {
		String clientId = "...";// 애플리케이션 클라이언트 아이디값";
		String clientSecret = "...";// 애플리케이션 클라이언트 시크릿값";
		try {
			String code = "0"; // 키 발급시 0, 캡차 이미지 비교시 1로 세팅
			String apiURL = "https://naveropenapi.apigw.ntruss.com/captcha/v1/nkey?code=" + code;
			URL url = new URL(apiURL);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
			con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
			int responseCode = con.getResponseCode();
			BufferedReader br;
			if (responseCode == 200) { // 정상 호출
				br = new BufferedReader(new InputStreamReader(con.getInputStream()));
			} else { // 오류 발생
				br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
			}
			String inputLine;
			StringBuffer response = new StringBuffer();
			while ((inputLine = br.readLine()) != null) {
				response.append(inputLine);
			}
			br.close();
			System.out.println(response.toString());
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
上記のコードでsetRequestPropertyに指定された値は、要求されたjspからreqeust.getHeader()を抽出することができる.すなわち,セキュリティ情報は要求主体ではなくヘッダ情報によって伝達される.InputStreamReader:InputStreamのバイトレベルI/OをReaderの文字レベルI/Oに変換します.△この場合、3文字を交換することもできます.BufferedReader:1行1行を書くreadline()関数java.net.URL:ajaxと同様に、リクエストを発行して応答を受け入れることができます.
(ajaxとは異なり、要求が発行され、応答が待機する非同期ではありません.)

キャプチャ画像の受信

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Test907 {
    public static void main(String[] args) {
        String clientId = "...";//애플리케이션 클라이언트 아이디값";
        try {
            String key = "..."; // https://naveropenapi.apigw.ntruss.com/captcha/v1/nkey 호출로 받은 키값
            String apiURL = "https://naveropenapi.apigw.ntruss.com/captcha-bin/v1/ncaptcha?key=" + key + "&X-NCP-APIGW-API-KEY-ID" + clientId;
            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if(responseCode==200) { // 정상 호출
                InputStream is = con.getInputStream();
                int read = 0;
                byte[] bytes = new byte[1024];
                // 랜덤한 이름으로 파일 생성
                String tempname = Long.valueOf(new Date().getTime()).toString();
                File f = new File( Util.upload() + tempname + ".jpg");
                f.createNewFile();
                OutputStream outputStream = new FileOutputStream(f);
                while ((read =is.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                is.close();
            } else {  // 오류 발생
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = br.readLine()) != null) {
                    response.append(inputLine);
                }
                br.close();
                System.out.println(response.toString());
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
指定したフォルダに画像が保存されていることを確認します

入力値の比較

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test908 {
    public static void main(String[] args) {
        String clientId = "...";//애플리케이션 클라이언트 아이디값";
        String clientSecret = "...";//애플리케이션 클라이언트 시크릿값";
        try {
            String code = "1"; // 키 발급시 0,  캡차 이미지 비교시 1로 세팅
            String key = "..."; // 캡차 키 발급시 받은 키값
            String value = "..."; // 사용자가 입력한 캡차 이미지 글자값
            String apiURL = "https://naveropenapi.apigw.ntruss.com/captcha/v1/nkey?code=" + code +"&key="+ key + "&value="+ value;

            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
            con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if(responseCode==200) { // 정상 호출
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {  // 오류 발생
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
            System.out.println(response.toString());
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
結果はtrue/flase

CAPTCHA & Servlet

project p0124_2:CATCHAとサーブレットの併用
public class Test909 extends HttpServlet {
	@Override
	public void service(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException 
	{
		String clientId = "...";// 애플리케이션 클라이언트 아이디값";
		String clientSecret = "...";// 애플리케이션 클라이언트 시크릿값";
		String key = null;
		try {
			String code = "0"; // 키 발급시 0, 캡차 이미지 비교시 1로 세팅
			String apiURL = "https://naveropenapi.apigw.ntruss.com/captcha/v1/nkey?code=" + code;
			URL url = new URL(apiURL);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
			con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
			int responseCode = con.getResponseCode();
			BufferedReader br;
			if (responseCode == 200) { // 정상 호출
				br = new BufferedReader(new InputStreamReader(con.getInputStream()));
			} else { // 오류 발생
				br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
			}
			String inputLine;
			StringBuffer sb = new StringBuffer();
			while ((inputLine = br.readLine()) != null) {
				sb.append(inputLine);
			}
			br.close();
			
			JSONObject jo = new JSONObject(sb.toString());
			key = jo.getString("key");
			
		} catch (Exception e) {
			System.out.println(e);
		}
		
		String tempname = null;
        	try {
            		String apiURL = "https://naveropenapi.apigw.ntruss.com/captcha-bin/v1/ncaptcha?key=" + key + "&X-NCP-APIGW-API-KEY-ID" + clientId;
           		URL url = new URL(apiURL);
            		HttpURLConnection con = (HttpURLConnection)url.openConnection();
            		con.setRequestMethod("GET");
            		int responseCode = con.getResponseCode();
            		BufferedReader br;
            		if(responseCode==200) { // 정상 호출
                		InputStream is = con.getInputStream();
                		int read = 0;
                		byte[] bytes = new byte[1024];
                		// 랜덤한 이름으로 파일 생성
                		tempname = Long.valueOf(new Date().getTime()).toString();
               			File f = new File( Util.upload() + tempname + ".jpg");
                		f.createNewFile();
                		OutputStream outputStream = new FileOutputStream(f);
                		while ((read =is.read(bytes)) != -1) {
                    		outputStream.write(bytes, 0, read);
                	}
                	is.close();
            		} else {  // 오류 발생
                		br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                		String inputLine;
                		StringBuffer sb = new StringBuffer();
                		while ((inputLine = br.readLine()) != null) {
                    			sb.append(inputLine);
                		}
                		br.close();
                		System.out.println(sb.toString());
            		}
        	} catch (Exception e) {
            		System.out.println(e);
        	}
		
		request.setAttribute("key", key );
		request.setAttribute("fname", tempname );
		RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/test_909_1.jsp");
		rd.forward(request, response);
	}
}
test 909 1は、送信するキー値と保存時に使用するファイル名を指定する.jspで転送/WEB-INF/test_909_1.jsp
<body>
	${key}<br/>
	<img src="image.jsp?fname=${fname}"/>
	<br/>
	<form method="POST" action="test910">
		<input type="hidden" name="key" value="${key}"/>
		<input type="text" name="captcha"/> 
		<input type="submit"/>
	</form>
</body>
${key}、${fnameの値を受け入れて、次の画面を実現します.
action="test910"
public class Test910 extends HttpServlet {
	@Override
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException 
	{
		String clientId = "...";
		String clientSecret = "...";
		// jsp 로부터 key 값 받아오기
		String key = request.getParameter("key");
        	// jsp 로부터 captcha 값 받아오기
		String value = request.getParameter("captcha");
		
		boolean result = false;
		try {
        		String code = "1"; // 키 발급시 0,  캡차 이미지 비교시 1로 세팅
            		String apiURL = "https://naveropenapi.apigw.ntruss.com/captcha/v1/nkey?code=" + code +"&key="+ key + "&value="+ value;

            		URL url = new URL(apiURL);
            		HttpURLConnection con = (HttpURLConnection)url.openConnection();
            		con.setRequestMethod("GET");
            		con.setRequestProperty("X-NCP-APIGW-API-KEY-ID", clientId);
            		con.setRequestProperty("X-NCP-APIGW-API-KEY", clientSecret);
            		int responseCode = con.getResponseCode();
            		BufferedReader br;
            		if(responseCode==200) { // 정상 호출
                		br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            		} else {  // 오류 발생
                		br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            		}
            		String inputLine;
           		StringBuffer sb = new StringBuffer();
            		while ((inputLine = br.readLine()) != null) {
                		sb.append(inputLine);
            		}
            		br.close();
            
            		JSONObject jo = new JSONObject(sb.toString());
            		// 사용자가 text박스 에 입력한 값과 captcha 이미지 안의 값이 같으면 true  
            		result = jo.getBoolean("result");
            
       		} catch (Exception e) {
           		System.out.println(e);
        	}
		System.out.println( result );
	}
}

textタイプのinputにキャプチャ画像の値を入力し、「≪発行|Submit|emdw≫」をクリックします.Test910コードを実行してコンソールウィンドウにtrueを表示します.