package com.test.common.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HttpsURLConnector {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public JSONObject postURL ( String urlData , Map<String, Object> headers , Map<String, Object> param) {
JSONObject jsonResult = new JSONObject();
//Http 요청시 필요한 URL 주소의 변수 선언
String totalUrl = "";
totalUrl = urlData.trim().toString();
// http 통신 객체 선언
URL url = null;
HttpsURLConnection httpConn = null;
// http 통신 응답에 대한 변수
String resData = "";
BufferedReader buff = null;
StringBuffer strBuff = null;
// 호출 결과값에 대한 변수
String returnData = "";
try {
ObjectMapper mapper = new ObjectMapper();
String paramData = mapper.writeValueAsString(param);
// url.openConnection을 시도하기 전에 아래 설정을 완료한다
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
} };
SSLContext sslContext;
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
// 파라미터로 들어온 url을 사용하여 connection 시도
url = new URL(totalUrl);
httpConn = (HttpsURLConnection) url.openConnection();
httpConn.setHostnameVerifier(new HostnameVerifier( ) {
@Override
public boolean verify(String hostname, SSLSession session) {
// return true로 해주어야 모든 SSL 검증을 무시함
return true;
}
});
// http 요청 설정
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/json; utf-8");
httpConn.setRequestProperty("Accept", "application/json");
// header 파라미터 설정
if ( headers != null ) {
for ( Map.Entry<String, Object> header : headers.entrySet()) {
httpConn.setRequestProperty(header.getKey(), header.getValue().toString());
}
}
// Body부 생성 - doOutPut을 true로 주어야함
httpConn.setDoOutput(true);
try (OutputStream os = httpConn.getOutputStream() ){
byte requestData[] = paramData.getBytes("utf-8");
os.write(requestData);
os.close();
} catch ( Exception e) {
logger.error("== OutputStream ERROR ::::: " + e.getMessage());
}
//커넥션~
httpConn.connect();
// 응답에 대한 데이터를 Buffer로 받아 처리
buff = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
strBuff = new StringBuffer();
while ( ( resData = buff.readLine() ) != null ) {
strBuff.append(resData); // StringBuffer에 응답받은 데이터를 순차적으로 저장함
}
returnData = strBuff.toString();
//https 응답코드
String resCode = String.valueOf(httpConn.getResponseCode());
JSONParser parser = new JSONParser();
Object obj = new Object();
try {
obj = parser.parse(strBuff.toString());
} catch (Exception e) {
logger.error("StringBuff Parser ERROR ::::: " + e.getMessage());
}
jsonResult = (JSONObject) obj;
} catch (Exception e) {
logger.error("TOTAL Error ::::: " + e.getMessage());
}
return jsonResult;
}
}