스프링 - 핸드폰 문자 보내기 구현해보기

Back-End/Spring 2019. 7. 31. 15:03

1. https://www.coolsms.co.kr/ 에서 회원가입 하기 (300포인트를 주는데 15건정도 보낼수 있음)


2. coolsms에 개발자센터 (https://www.coolsms.co.kr/developer)에 들어가서 api_key와 api_secret를 생성하고, api를 다운받는다.


* SDK -> JAVA -> JAVA SDK v2.1에 들어가서 순서대로 따라한다.










위 처럼 SDK를 다운받아도 되고, 메이븐저장소에서 다운로드 받아 추가해도 된다.


pom.xml에 라이브러리를 추가

1
2
3
4
5
<dependency>
    <groupId>net.nurigo</groupId>
    <artifactId>javaSDK</artifactId>
    <version>2.2</version>
</dependency>
cs




api와 예제를 참고해서 만들어보기


(예제 관련 참고 주소 : https://www.coolsms.co.kr/JAVA_SDK_Example)




====================================코드 부분===============================



view파일에 코드추가 (home.jsp 중 일부)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- 문자보내는 폼 -->
<form method="post" id="smsForm">
<table border = "1" align="right" width = "300" height = "200" >
 
<tr>
<td>
<center>
<br>
<span style="color: green; font-weight: bold;">SMS 전송 (문자보내기)</span>
 </center>
    <ul>
      <li>보낼사람 : <input type="text" name="from" placeholder=" 전화번호 입력 ( '-' 포함 )"/></li><br>
      <li>내용 : <textarea name="text" placeholder=" 보낼 내용 입력 "></textarea>    </li><br>
      <center>
      <input type="button" onclick="sendSMS('sendSms')" value="전송하기" /><br>
      </center>
    </ul>
 
    </td>
    </tr>
    </table>
  </form>
 
  <script>
    function sendSMS(pageName){
 
        console.log("문자를 전송합니다.");
        $("#smsForm").attr("action", pageName + ".do"); //위에 있는 폼태그를 컨트롤러로 전송한다.
        $("#smsForm").submit();
    }
  </script>
cs




컨트롤러 (MemberController.java 중 일부)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//문자를 보낼때 맵핑되는 메소드
        @RequestMapping(value = "/sendSms.do")
          public String sendSms(HttpServletRequest request) throws Exception {
 
            String api_key = "NCS0VWZPZQPVXEXX"; //위에서 받은 api key를 추가
            String api_secret = "DKTPX4RYWG5GEDPL6DMRRNKOJMATK24X"; //위에서 받은 api secret를 추가

            com.example.hansub_project.Coolsms coolsms = new com.example.hansub_project.Coolsms(api_key, api_secret);
//이 부분은 홈페이지에서 받은 자바파일을 추가한다음 그 클래스를 import해야 쓸 수 있는 클래스이다.
 
            HashMap<StringString> set = new HashMap<StringString>();
            set.put("to""01072851455"); // 수신번호
 
            set.put("from", (String)request.getParameter("from")); // 발신번호, jsp에서 전송한 발신번호를 받아 map에 저장한다.
            set.put("text", (String)request.getParameter("text")); // 문자내용, jsp에서 전송한 문자내용을 받아 map에 저장한다.
            set.put("type""sms"); // 문자 타입
 
            System.out.println(set);
 
            JSONObject result = coolsms.send(set); // 보내기&전송결과받기
 
            if ((boolean)result.get("status"== true) {

              // 메시지 보내기 성공 및 전송결과 출력
              System.out.println("성공");
              System.out.println(result.get("group_id")); // 그룹아이디
              System.out.println(result.get("result_code")); // 결과코드
              System.out.println(result.get("result_message")); // 결과 메시지
              System.out.println(result.get("success_count")); // 메시지아이디
              System.out.println(result.get("error_count")); // 여러개 보낼시 오류난 메시지 수
            } else {

              // 메시지 보내기 실패
              System.out.println("실패");
              System.out.println(result.get("code")); // REST API 에러코드
              System.out.println(result.get("message")); // 에러메시지
            }
 
            return "member/number"; //문자 메시지 발송 성공했을때 number페이지로 이동함
          }
cs



Https.java 파일 작성 (Https request, response를 관리하는 클래스)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package com.example.hansub_project;
 
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.util.Random;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
 
/*
 * Https.class
 * Https request, response를 관리하는 class 입니다.
 */
public class Https
{
    /*
     * postRequest (POST)
     * @param StringBuffer : data 
     * @param String : image
     */
    public JSONObject postRequest(String url_string, HashMap<StringString> params) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("status"false);
 
            String salt = salt();
            String timestamp = getTimestamp();
            String signature = getSignature(params.get("api_secret"), salt, timestamp); 
            String boundary = salt + timestamp;
            String delimiter = "\r\n--" + boundary + "\r\n";
 
            params.put("salt", salt);
            params.put("signature", signature);
            params.put("timestamp", timestamp);
 
            // data 생성 및 데이터 구분을 위한 delimiter 설정
            StringBuffer postDataBuilder = new StringBuffer();
            postDataBuilder.append(delimiter);
 
            // params에 image가 있으면 변수에 담아 request를 다르게 보낸다
            String image = null;
            String image_path = null;
            for (Entry<StringString> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                
                if (key == "image") {
                    image = value;
                    continue;
                }                
                if (key == "image_path") {
                    image_path = value;
                    continue;
                }                
                postDataBuilder = setPostData(postDataBuilder, key, value, delimiter);
                if(postDataBuilder == null) {
                    obj.put("message""postRequest data build fail");
                       return obj;
                }
            }
            
            URL url = new URL(url_string);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // connect
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection""Keep-Alive");
            connection.setRequestProperty("Content-Type""multipart/form-data;boundary=" + boundary);
            connection.setUseCaches(false);
            DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(connection.getOutputStream()));
 
            // image data set
            if(image != null) {
                // MMS Setting
                if(image_path == null) image_path = "./";
                
                // image file set
                postDataBuilder.append(setFile("image", image));                
                postDataBuilder.append("\r\n");
                FileInputStream fileStream = new FileInputStream(image_path + image);
                outputStream.writeUTF(postDataBuilder.toString());
                
                // 파일전송 작업 시작
                int maxBufferSize = 1024;
                int bufferSize = Math.min(fileStream.available(), maxBufferSize);
                byte[] buffer = new byte[bufferSize];
                // 버퍼 크기만큼 파일로부터 바이트 데이터를 읽는다
                int byteRead = fileStream.read(buffer, 0, bufferSize);
                // 전송
                while (byteRead > 0) {
                    outputStream.write(buffer);
                    bufferSize = Math.min(fileStream.available(), maxBufferSize);
                    byteRead = fileStream.read(buffer, 0, bufferSize);
                }
                fileStream.close();
            } else {
                outputStream.writeUTF(postDataBuilder.toString());
            }
            outputStream.writeBytes(delimiter); 
            outputStream.flush();
            outputStream.close();
 
            String response = null;
            String inputLine; 
            int response_code = connection.getResponseCode();
            BufferedReader in = null;
            // response 담기 
            if (response_code != 200) {
                in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            }
 
            while ((inputLine = in.readLine()) != null) {                    
                response = inputLine;
            }
 
            if (response != null) {
                obj = (JSONObject) JSONValue.parse(response);
                obj.put("status"true);
                if (obj.get("code"!= null) {
                    obj.put("status"false);
                }
            } else {
                obj.put("status"false);
                obj.put("message""response is empty");
            }
        } catch (Exception e) {
            obj.put("status"false);
            obj.put("message", e.toString());
        }
        return obj;
    }
 
    /*
     * https request (GET)
     */
    public JSONObject request(String url_string, HashMap<StringString> params) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("status"true);
            String charset = "UTF8";
            String salt = salt();
            String timestamp = getTimestamp();
            String signature = getSignature(params.get("api_secret"), salt, timestamp); // getSignature
 
            String data = url_string + "?";
            data = data + URLEncoder.encode("api_key", charset) + "=" + URLEncoder.encode(params.get("api_key"), charset);
            data = setGetData(data, "signature", signature, charset);
            data = setGetData(data, "salt", salt, charset);
            data = setGetData(data, "timestamp", timestamp, charset);
 
            params.remove("api_secret");
 
            for (Entry<StringString> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                data = setGetData(data, key, value, charset);
                if(data == null) {
                    obj.put("status"false);
                    obj.put("message""request data build fail");
                       return obj;
                }
            }
 
            URL url = new URL(data);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // connect
            connection.setRequestMethod("GET");
            
            BufferedReader in = null;
            int response_code = connection.getResponseCode();
            if (response_code != 200) {
                // 오류발생시
                in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            }
 
            String response = null;
            String inputLine; // 서버로 부터 받은 response를 받을 변수
            while ((inputLine = in.readLine()) != null) {
                response = inputLine;
            }
 
            if (response != null) {
                // response 가 object 냐 array에 따라 parse를 다르게한다.
                try {
                    obj = (JSONObject) JSONValue.parse(response);
                } catch (Exception e) {
                    try {
                        JSONArray reponse_array = (JSONArray) JSONValue.parse(response);
                        obj.put("data", reponse_array);
                    } catch (Exception ex) {
                        obj.put("status"false);
                    }
                }
                obj.put("status"true);
                if (obj.get("code"!= null) {
                    obj.put("status"false);
                }
            } else {
                obj.put("status"false);
                obj.put("message""response is empty");
            }
        } catch (Exception e) {
            obj.put("status"false);
            obj.put("message", e.toString());
        }
        return obj;
    }
 
    /*
     * 업로드할 파일에 대한 메타 데이터를 설정한다.
     * @param key : 서버에서 사용할 파일 변수명
     * @param fileName : 서버에서 저장될 파일명
     */
    public String setFile(String key, String fileName) {
        return "Content-Disposition: form-data; name=\"" + key
                + "\";filename=\"" + fileName
                + "\"\r\nContent-type: image/jpeg;\r\n";
    }
 
    /*
     * String을 POST 형식에 맞게 Input 
     */
    public StringBuffer setPostData(StringBuffer builder, String key, String value, String delimiter) {
        try {
            builder.append(setValue(key, value));
            builder.append(delimiter);
        } catch(Exception e) {
            return null;
        }
 
        return builder;
    }
 
    /*
     * String을 GET 방식으로 변경
     */
    public String setGetData(String data, String key, String value, String charSet) {
        try {
            data += "&"
                + URLEncoder.encode(key, charSet)
                + "="
                + URLEncoder.encode(value, charSet);
        } catch(Exception e) {
            return null;
        }
 
        return data;
    }
 
    /*
     * Get salt
     */
    public String salt() {
        String uniqId = "";
        Random randomGenerator = new Random();
 
        // length - set the unique Id length
        for (int length = 1length <= 10++length) {
            int randomInt = randomGenerator.nextInt(10); // digit range from 0 - 9
            uniqId += randomInt + "";
        }
 
        return uniqId;
    }
 
    /*
     * Get signature
     */
    public String getSignature(String api_secret, String salt, String timestamp) {
        String signature = "";
        
        try {
            String temp = timestamp + salt;
            SecretKeySpec keySpec = new SecretKeySpec(api_secret.getBytes(), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(keySpec);
 
            byte[] result = mac.doFinal(temp.getBytes());
            char[] hexArray = "0123456789ABCDEF".toCharArray();
            char[] hexChars = new char[result.length * 2];
 
            for (int i = 0; i < result.length; i++) {
                int positive = result[i] & 0xff;
                hexChars[i * 2= hexArray[positive >>> 4];
                hexChars[i * 2 + 1= hexArray[positive & 0x0F];
            }
            signature = new String(hexChars);
        } catch (Exception e) {
            signature = e.getMessage();
        }
 
        return signature;
    }
 
    /*
     * Get timestamp
     */
    public String getTimestamp() {
        long timestamp_long = System.currentTimeMillis() / 1000;
        String timestamp = Long.toString(timestamp_long);
        return timestamp;
    }
 
    /*
     * Map 형식으로 Key와 Value를 셋팅한다.
     * @param key : 서버에서 사용할 변수명
     * @param value : 변수명에 해당하는 실제 값
     */
    public String setValue(String key, String value) {
        return "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n"+ value;
    }
}
 
cs



Coolsms.java (Coolsms 클래스, 문자 전송을 위한 coolsms관련 메소드를 사용하기 위한 클래스)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package com.example.hansub_project;
 
import java.io.*;
import java.net.URLEncoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.util.Properties;
import java.util.Random;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
 
/*
 * Coolsms Class
 * RestApi JAVA 
 * v1.1 
 * POST?GET REQUEST
 */
public class Coolsms extends Https {
    final String URL = "https://api.coolsms.co.kr";
    private String sms_url = URL + "/sms/1.5/";
    private String senderid_url = URL + "/senderid/1.1/";
    private String api_key;
    private String api_secret;    
    private String timestamp;
    private Https https = new Https();
    Properties properties = System.getProperties();
 
    /*
     * Set api_key, api_secret
     */
    public Coolsms(String api_key, String api_secret) {
        this.api_key = api_key;
        this.api_secret = api_secret;
    }
    
    /*
     * Send messages
     * @param set : HashMap<String, String>
     */
    public JSONObject send(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            params.put("os_platform", properties.getProperty("os_name"));
            params.put("dev_lang""JAVA " + properties.getProperty("java.version"));
            params.put("sdk_version""JAVA SDK 1.1");
 
            // Send message 
            response = https.postRequest(sms_url + "send", params);    
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
    
    /*
     * Sent messages
     * @param set : HashMap<String, String>
     */
    public JSONObject sent(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            
            response = https.request(sms_url + "sent", params); // GET방식 전송    
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Reserve message cancel 
     * @param set : HashMap<String, String>
     */
    public JSONObject cancel(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            
            // Cancel reserve message 
            response = https.postRequest(sms_url + "cancel", params);    
 
            // Cancel은 response 가 empty 면 성공
            if (response.get("message"== "response is empty") {
                response.put("status"true);
                response.put("message"null);
            }
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Balance info
     */
    public JSONObject balance() {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            HashMap<StringString> params = new HashMap<StringString>();
            params = setBasicInfo(params);
 
            // GET방식 전송    
            response = https.request(sms_url + "balance", params); // GET방식 전송    
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Register sender number
     * @param set : HashMap<String, String>
     */
    public JSONObject register(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            
            // Register sender number request
            response = https.postRequest(senderid_url + "register", params);    
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Verify sender number
     * @param set : HashMap<String, String>
     */
    public JSONObject verify(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            
            // Register verify sender number 
            response = https.postRequest(senderid_url + "verify", params);    
            if (response.get("message"== "response is empty") {
                response.put("status"true);
                response.put("message"null);
            }
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Delete sender number
     * @param set : HashMap<String, String>
     */
    public JSONObject delete(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            
            // Register delete sender number 
            response = https.postRequest(senderid_url + "delete", params);    
            if (response.get("message"== "response is empty") {
                response.put("status"true);
                response.put("message"null);
            }
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Set default sender number
     * @param set : HashMap<String, String>
     */
    public JSONObject setDefault(HashMap<StringString> params) {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            params = setBasicInfo(params);
            
            // Register set default sender number 
            response = https.postRequest(senderid_url + "set_default", params);    
            if (response.get("message"== "response is empty") {
                response.put("status"true);
                response.put("message"null);
            }
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Get sender number list
     * @param set : HashMap<String, String>
     */
    public JSONObject list() {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            HashMap<StringString> params = new HashMap<StringString>();
            params = setBasicInfo(params);
            
            // Register sender number request
            response = https.request(senderid_url + "list", params);    
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Get default sender number
     * @param set : HashMap<String, String>
     */
    public JSONObject getDefault() {
        JSONObject response = new JSONObject();
        try {
            // 기본정보 입력
            HashMap<StringString> params = new HashMap<StringString>();
            params = setBasicInfo(params);
            
            // Get default sender number 
            response = https.request(senderid_url + "get_default", params);    
        } catch (Exception e) {
            response.put("status"false);
            response.put("message", e.toString());
        }
        return response;
    }
 
    /*
     * Set api_key and api_secret.
     * @param set : HashMap<String, String>
     */
    private HashMap<StringString> setBasicInfo(HashMap<StringString> params) {
        params.put("api_secret"this.api_secret);
        params.put("api_key"this.api_key);
        return params;
    }
}
 
cs










출처

https://seonhyungjo.github.io/Spring-SMS/

: