티스토리 뷰
728x90
반응형
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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | package klago.gw.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Map; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import org.apache.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class AuthCallUtil { public static String responseConn(HttpURLConnection connection) { try { int responseCode = connection.getResponseCode(); StringBuilder sb = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"), 8); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); } else { return UnAuthCallUtil.readInputStream(connection.getErrorStream()); } connection.disconnect(); return sb.toString(); }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.responseConn-Error : ", e); e.printStackTrace(); } return null; } public static void writeFileHeader(ArrayList<File> filesAL, PrintWriter writer, OutputStream outputStream, ArrayList<String> fileHeaders, String lineEnd, String tail) { try { int bytesRead; int maxBufferSize = 1024; byte buf[] = new byte[maxBufferSize]; int filesAlSize = filesAL.size(); for (int i = 0; i < filesAlSize; i++) { writer.append(fileHeaders.get(i)); writer.flush(); BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filesAL.get(i))); while ((bytesRead = bufferedInputStream.read(buf)) != -1) { outputStream.write(buf, 0, bytesRead); writer.flush(); } outputStream.write(lineEnd.getBytes()); outputStream.flush(); bufferedInputStream.close(); } writer.append(tail); writer.flush(); writer.close(); outputStream.close(); }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.writeFileHeader-Error : ", e); e.printStackTrace(); } } public static void writeParamHeader(ArrayList<String> paramHeaders, PrintWriter writer) { for (int i = 0; i < paramHeaders.size(); i++) { writer.append(paramHeaders.get(i)); writer.flush(); } } public static String[] setFileToFileHeader(Map<String, String> files, String twoHypen, String boundary, String lineEnd, long fileLength, String filePart, String charset, ArrayList<String> fileHeaders, ArrayList<File> filesAL){ String fileHeader = null; try { for (Map.Entry<String, String> entry : files.entrySet()) { File file = new File(entry.getValue()); fileHeader = twoHypen + boundary + lineEnd + "Content-Disposition: form-data; name=\"" + "file[]" + "\"; filename=\"" + file.getName() + "\"" + lineEnd + "Content-Type: " + URLConnection.guessContentTypeFromName(file.getAbsolutePath()) + lineEnd + "Content-Transfer-Encoding: binary" + lineEnd + lineEnd; fileLength += file.length() + lineEnd.getBytes(charset).length; filePart += fileHeader; fileHeaders.add(fileHeader); filesAL.add(file); } return new String[] {filePart, String.valueOf(fileLength)}; }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.setFileUpload-Error : ", e); e.printStackTrace(); } return null; } public static String setParamToParamHeader(Map<String, String> params, String twoHypen, String boundary, String lineEnd, String charset, String paramsPart, ArrayList<String> paramHeaders) { for (Map.Entry<String, String> entry : params.entrySet()) { String param = twoHypen + boundary + lineEnd + "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + lineEnd + "Content-Type: text/plain; charset=" + charset + lineEnd + lineEnd + entry.getValue() + lineEnd; paramsPart += param; paramHeaders.add(param); } return paramsPart; } public static String upload(Map<String, String> params, Map<String, String> files, HttpURLConnection connection, String boundary) throws IOException { final String lineEnd = "\r\n"; final String twoHypen = "--"; final String tail = lineEnd + twoHypen + boundary + twoHypen + lineEnd; String charset = "UTF-8"; String paramsPart = ""; String filePart = ""; String partData = null; String[] filePartAndFileLen = null; long fileLength = 0; long requestLength = 0; OutputStream outputStream = null; PrintWriter writer = null; ArrayList<String> paramHeaders = new ArrayList<>(); ArrayList<File> filesAL = new ArrayList<>(); ArrayList<String> fileHeaders = new ArrayList<>(); paramsPart = setParamToParamHeader(params, twoHypen, boundary, lineEnd, charset, paramsPart, paramHeaders); filePartAndFileLen = setFileToFileHeader(files, twoHypen, boundary, lineEnd, fileLength, filePart, charset, fileHeaders, filesAL); if(filePartAndFileLen != null) { filePart = filePartAndFileLen[0]; fileLength = Long.parseLong(filePartAndFileLen[1]); } partData = paramsPart + filePart; requestLength = partData.getBytes(charset).length + fileLength + tail.getBytes(charset).length; connection.setRequestProperty("Content-length", "" + requestLength); connection.setFixedLengthStreamingMode((int) requestLength); connection.connect(); outputStream = new BufferedOutputStream(connection.getOutputStream()); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); writeParamHeader(paramHeaders, writer); writeFileHeader(filesAL, writer, outputStream, fileHeaders, lineEnd, tail); return responseConn(connection); } public static HttpURLConnection setUploadConn(String requestURL, String boundary, HttpURLConnection connection) { try { URL url = new URL(requestURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); return connection; }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.setUploadConn-Error : ", e); e.printStackTrace(); } return null; } public static String checkResponseCode(HttpURLConnection connection, String result) { try { final int responseCode = connection.getResponseCode(); if (responseCode / 100 != 2) { // 400, 401, 501 result = UnAuthCallUtil.readInputStream(connection.getErrorStream()); }else{ result = UnAuthCallUtil.readInputStream(connection.getInputStream()); } }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.checkResponseCode-Error : ", e); e.printStackTrace(); } return result; } public static HttpURLConnection openConnection(String url) { try { return (HttpURLConnection) new URL(url).openConnection(); }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.openConnection-Error : ", e); e.printStackTrace(); } return null; } public static void setPostRequestContentType(HttpURLConnection connection, int requestBodyParamChk) { if(requestBodyParamChk == 0) { connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); }else { //connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + makeDelimeter()); connection.setRequestProperty("Content-type", "application/json"); } } public static void writePostDataToOutStream(HttpURLConnection connection, int requestBodyParamChk, Map<String, Object> param) { try { final OutputStream out = connection.getOutputStream(); if(requestBodyParamChk == 0) { out.write(UnAuthCallUtil.postDataToBytes(param)); }else { out.write(UnAuthCallUtil.getJsonStringFromMap(param).toJSONString().getBytes()); } out.flush(); out.close(); }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.writePostDataToOutStream-Error : ", e); e.printStackTrace(); } } public static void setEtcConnectionPropAndConnect(HttpURLConnection connection, String method, String url, JSONObject headerParamObj, String transactionId) { try { connection.setConnectTimeout(UnAuthCallUtil.CONNECTION_TIMEOUT); connection.setRequestMethod(method); setEtcProperty(connection, url, headerParamObj, transactionId); }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.setEtcConnectionPropAndConnect-Error : ", e); e.printStackTrace(); } } public static String getApiUrl(String url) { String[] urlSplit = url.split("/", -1); String apiUrl = null; if(urlSplit.length > 4) { apiUrl = "/" + urlSplit[3] + "/" + urlSplit[4]; } return apiUrl; } public static String makeDelimeter() { return "===" + System.currentTimeMillis() + "==="; } public static JSONObject jsonStringToJsonObj(String jsonStr) { try { JSONObject parseObj = null; if(jsonStr != null) { parseObj = (JSONObject) new JSONParser().parse(jsonStr); } if(parseObj != null) { return (JSONObject) parseObj.get("resultData"); } }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.jsonStringToJsonObj-Error : ", e); e.printStackTrace(); } return null; } public static String hmac(String key, String value) { try { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] encrypted = mac.doFinal(value.getBytes(StandardCharsets.UTF_8)); String base64Binary = DatatypeConverter.printBase64Binary(encrypted); return base64Binary; }catch(Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.hmac-Error : ", e); e.printStackTrace(); } return null; } public static String execute(String method, String url, Map<String, Object> param, String headerParam, int requestBodyParamChk) { HttpURLConnection connection = null; String result =""; int methodCase = 0; String transactionId = UnAuthCallUtil.makeTransactionId(); JSONObject headerParamObj = jsonStringToJsonObj(headerParam); if(headerParamObj == null) { result = "{\"error\": headerParamObj is null}"; return result; } if(url == null || url.equals("")) { result = "{\"error\": url이 없습니다}"; return result; } if(method == null || method.equals("")) { result = "{\"error\": method가 없습니다}"; return result; } if(requestBodyParamChk > 1 || requestBodyParamChk < 0) { requestBodyParamChk = 0; } if(method.toUpperCase().equals("POST")) { methodCase = 1; } try { switch (methodCase) { //GET case 0: if(param != null) { connection = openConnection(url.concat("?").concat(UnAuthCallUtil.formEncode(param))); }else { connection = openConnection(url); } setEtcConnectionPropAndConnect(connection, method, url, headerParamObj, transactionId); connection.connect(); break; //POST case 1: connection = openConnection(url); connection.setDoOutput(true); setPostRequestContentType(connection, requestBodyParamChk); setEtcConnectionPropAndConnect(connection, method, url, headerParamObj, transactionId); connection.connect(); if(param != null) { writePostDataToOutStream(connection, requestBodyParamChk, param); } break; } result = checkResponseCode(connection, result); } catch (Exception e) { Logger.getLogger( AuthCallUtil.class ).error( "AuthCallUtil.execute--Error : ", e); result = "{\"error\": " + e + "}"; return result; } finally { if (connection != null) connection.disconnect(); } return result; } public static String executeUpload(Map<String, String> param, Map<String, String> files, String url, String headerParam) throws IOException, ClassNotFoundException { final String boundary = makeDelimeter(); String transactionId = UnAuthCallUtil.makeTransactionId(); JSONObject headerParamObj = jsonStringToJsonObj(headerParam); HttpURLConnection connection = null; String result = null; if(headerParamObj == null) { result = "{\"error\": headerParamObj is null}"; return result; } if(url == null || url.equals("")) { result = "{\"error\": url이 없습니다}"; return result; } connection = setUploadConn(url, boundary, connection); setEtcConnectionPropAndConnect(connection, "POST", url, headerParamObj, transactionId); return upload(param, files, connection, boundary); } } | cs |
728x90
반응형
'Java' 카테고리의 다른 글
[Java & JavaScript] Java에서 JSONObject에 htmlCode를 담아 프론트로 내려주고 JSON.parse() 메소드 사용시 에러날때 (0) | 2020.04.06 |
---|---|
[Java] HttpURLConnection을 이용하여 api 호출 (0) | 2020.04.06 |
[Java] json to map, map to json 등 (0) | 2020.04.06 |
[Java] UUID 생성 (0) | 2020.04.06 |
[Java] Cannot write output after reading input. (0) | 2020.04.06 |
댓글