Created
February 13, 2020 02:21
-
-
Save jeedy/990f1e79f8caa047b3562b29d382347f to your computer and use it in GitHub Desktop.
HttpsURLConnection 라이브러리로 API 통신을 위한 모듈 개발(httpclient로 통신되지 않을 경우)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jee; | |
import java.io.BufferedReader; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.security.cert.X509Certificate; | |
import javax.net.ssl.HttpsURLConnection; | |
import javax.net.ssl.SSLContext; | |
import javax.net.ssl.TrustManager; | |
import javax.net.ssl.X509TrustManager; | |
import org.apache.commons.logging.Log; | |
import org.apache.commons.logging.LogFactory; | |
import org.json.simple.JSONArray; | |
import org.json.simple.JSONObject; | |
import org.json.simple.parser.JSONParser; | |
import com.sun.xml.internal.messaging.saaj.util.Base64; | |
import com.jee.vo.ZendeskCreateTicketVO; | |
/** | |
* @author jeeyong | |
*/ | |
public class TestHttpsConnection { | |
private static final Log logger = LogFactory.getLog(TestHttpsConnection.class); | |
private static final String ZENDESK_URL = "https://jee.zendesk.com"; | |
private static final String ZENDESK_ACCOUNT_인증계정 = "xxx"; | |
private static final String ZENDESK_TOKEN_문의용 = "xzxx"; | |
/** | |
* Ticket 코멘트 가져오기 | |
* | |
*/ | |
@Override | |
public JSONObject getTicketComments(String ticketId) throws Exception { | |
JSONParser jsonParser = new JSONParser(); | |
return (JSONObject) jsonParser.parse( | |
sendHttpGet(ZENDESK_URL + "/api/v2/requests/" + ticketId + "/comments.json", ZENDESK_ACCOUNT_인증계정)); | |
} | |
/** | |
* 사용자 이메일를 기준으로 등록된 1:1문의(tickets) 가져온다. | |
* | |
* @param userEmail 유저 이메일 주소 | |
*/ | |
@Override | |
public JSONObject getTickets(String userEmail) throws Exception { | |
JSONParser jsonParser = new JSONParser(); | |
return (JSONObject) jsonParser.parse(sendHttpGet(ZENDESK_URL + "/api/v2/requests.json", userEmail)); | |
} | |
/** | |
* 사용자 1:1 문의 생성 | |
* | |
* @param req | |
*/ | |
@Override | |
public JSONObject createTicket(ZendeskCreateTicketVO ticket) throws Exception { | |
JSONObject root = new JSONObject(); | |
// request | |
JSONObject request = new JSONObject(); | |
root.put("request", request); | |
{ | |
// subject | |
request.put("subject", ticket.getSubject()); | |
// requester | |
JSONObject requester = new JSONObject(); | |
request.put("requester", requester); | |
requester.put("name", ticket.getName()); | |
requester.put("email", ticket.getEmail()); | |
// comment | |
JSONObject comment = new JSONObject(); | |
request.put("comment", comment); | |
comment.put("body", ticket.getBody()); | |
// comment.put("uplaods", uplaods); | |
{ | |
// 커스텀 필드값 | |
JSONArray custom_fields = new JSONArray(); | |
request.put("custom_fields", custom_fields); | |
JSONObject cf1 = new JSONObject(); | |
cf1.put("id", "1"); | |
cf1.put("value", ticket.getReserveId()); | |
custom_fields.add(cf1); | |
JSONObject cf2 = new JSONObject(); | |
cf2.put("id", "2"); | |
cf2.put("value", ticket.getServiceType()); | |
custom_fields.add(cf2); | |
JSONObject cf3 = new JSONObject(); | |
cf3.put("id", "3"); | |
cf3.put("value", ticket.getService()); | |
custom_fields.add(cf3); | |
JSONObject cf4 = new JSONObject(); | |
cf4.put("id", "4"); | |
cf4.put("value", ticket.getUserPhone()); | |
custom_fields.add(cf4); | |
JSONObject cf5 = new JSONObject(); | |
cf5.put("id", "5"); | |
cf5.put("value", ticket.getSendSMS()); | |
custom_fields.add(cf5); | |
} | |
} | |
logger.info("ZENDESK request:: " + root.toJSONString()); | |
// 1. Ticket 생성 | |
String responseString = sendHttpPost(ZENDESK_URL + "/api/v2/requests.json", root.toJSONString()); | |
JSONParser jsonParser = new JSONParser(); | |
JSONObject result = (JSONObject) jsonParser.parse(responseString); | |
logger.info("ZENDESK response:: " + responseString); | |
// 2. 사용자이메일 인증: 처음 등록되는 사용자는 이메일 인증이 되어야 검색가능하다. | |
if (result.containsKey("request")) { | |
Long requester_id = (Long) (((JSONObject) result.get("request")).get("requester_id")); | |
if (requester_id != null) { | |
responseString = sendHttpPut(ZENDESK_URL + "/api/v2/users/" + requester_id + ".json", | |
"{\"user\":{ \"verified\": true}}"); | |
logger.info("ZENDESK email verified response:: " + responseString); | |
} | |
} | |
return (JSONObject) jsonParser.parse(responseString); | |
} | |
public String sendHttpPut(String _url, String body) { | |
String plainCreds = String.format("%s/token:%s", ZENDESK_ACCOUNT_인증계정, ZENDESK_TOKEN_문의용); | |
byte[] base64CredsBytes = Base64.encode(plainCreds.getBytes()); | |
String base64Creds = new String(base64CredsBytes); | |
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { | |
public java.security.cert.X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
public void checkClientTrusted(X509Certificate[] certs, String authType) { | |
} | |
public void checkServerTrusted(X509Certificate[] certs, String authType) { | |
} | |
} }; | |
OutputStream os = null; | |
BufferedReader br = null; | |
InputStreamReader in = null; | |
HttpURLConnection con = null; | |
StringBuffer sb = new StringBuffer(); | |
try { | |
SSLContext sc = SSLContext.getInstance("SSL"); | |
sc.init(null, trustAllCerts, new java.security.SecureRandom()); | |
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); | |
URL url = new URL(_url); | |
java.lang.System.setProperty("https.protocols", "TLSv1.2"); | |
con = (HttpURLConnection) url.openConnection(); | |
con.setRequestMethod("PUT"); | |
con.setDoOutput(true); | |
con.setDoInput(true); | |
con.setUseCaches(false); | |
con.setDefaultUseCaches(false); | |
con.setConnectTimeout(300000); | |
con.setReadTimeout(300000); | |
con.setRequestProperty("Content-Type", "application/json"); | |
con.setRequestProperty("Authorization", "Basic " + base64Creds); | |
os = con.getOutputStream(); | |
os.write(body.getBytes("UTF-8")); | |
in = new InputStreamReader((InputStream) con.getContent()); | |
br = new BufferedReader(in); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
} catch (Exception e) { | |
/* | |
* status 200 이 아닌 400~500 에러일 경우 에러 body에 따로 담겨온다. | |
*/ | |
try { | |
in = new InputStreamReader((InputStream) con.getErrorStream()); | |
br = new BufferedReader(in); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
} catch (Exception e2) { | |
} | |
logger.error(e); | |
} finally { | |
try { | |
if (os != null) { | |
os.flush(); | |
os.close(); | |
} | |
if (br != null) { | |
br.close(); | |
} | |
if (in != null) { | |
in.close(); | |
} | |
if (con != null) { | |
con.disconnect(); | |
} | |
} catch (Exception e) { | |
} | |
} | |
return sb.toString(); | |
} | |
/** | |
* post 보내기 | |
* | |
* @param _url | |
* @param body | |
* @return | |
*/ | |
public String sendHttpPost(String _url, String body) { | |
String plainCreds = String.format("%s/token:%s", ZENDESK_ACCOUNT_인증계정, ZENDESK_TOKEN_문의용); | |
byte[] base64CredsBytes = Base64.encode(plainCreds.getBytes()); | |
String base64Creds = new String(base64CredsBytes); | |
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { | |
public java.security.cert.X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
public void checkClientTrusted(X509Certificate[] certs, String authType) { | |
} | |
public void checkServerTrusted(X509Certificate[] certs, String authType) { | |
} | |
} }; | |
OutputStream os = null; | |
BufferedReader br = null; | |
InputStreamReader in = null; | |
HttpURLConnection con = null; | |
StringBuffer sb = new StringBuffer(); | |
try { | |
SSLContext sc = SSLContext.getInstance("SSL"); | |
sc.init(null, trustAllCerts, new java.security.SecureRandom()); | |
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); | |
URL url = new URL(_url); | |
java.lang.System.setProperty("https.protocols", "TLSv1.2"); | |
con = (HttpURLConnection) url.openConnection(); | |
con.setRequestMethod("POST"); | |
con.setDoOutput(true); | |
con.setDoInput(true); | |
con.setUseCaches(false); | |
con.setDefaultUseCaches(false); | |
con.setConnectTimeout(300000); | |
con.setReadTimeout(300000); | |
con.setRequestProperty("Content-Type", "application/json"); | |
con.setRequestProperty("Authorization", "Basic " + base64Creds); | |
os = con.getOutputStream(); | |
os.write(body.getBytes("UTF-8")); | |
in = new InputStreamReader((InputStream) con.getContent()); | |
br = new BufferedReader(in); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
} catch (Exception e) { | |
/* | |
* status 200 이 아닌 400~500 에러일 경우 에러 body에 따로 담겨온다. | |
*/ | |
try { | |
in = new InputStreamReader((InputStream) con.getErrorStream()); | |
br = new BufferedReader(in); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
} catch (Exception e2) { | |
} | |
logger.error(e); | |
} finally { | |
try { | |
if (os != null) { | |
os.flush(); | |
os.close(); | |
} | |
if (br != null) { | |
br.close(); | |
} | |
if (in != null) { | |
in.close(); | |
} | |
if (con != null) { | |
con.disconnect(); | |
} | |
} catch (Exception e) { | |
} | |
} | |
return sb.toString(); | |
} | |
/** | |
* | |
* @param _url | |
* @param zendesk_user_email | |
* @return | |
*/ | |
public String sendHttpGet(String _url, String zendesk_user_email) { | |
String plainCreds = String.format("%s/token:%s", zendesk_user_email, ZENDESK_TOKEN_문의용); | |
byte[] base64CredsBytes = Base64.encode(plainCreds.getBytes()); | |
String base64Creds = new String(base64CredsBytes); | |
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { | |
public java.security.cert.X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
public void checkClientTrusted(X509Certificate[] certs, String authType) { | |
} | |
public void checkServerTrusted(X509Certificate[] certs, String authType) { | |
} | |
} }; | |
OutputStream os = null; | |
BufferedReader br = null; | |
InputStreamReader in = null; | |
HttpURLConnection con = null; | |
StringBuffer sb = new StringBuffer(); | |
try { | |
SSLContext sc = SSLContext.getInstance("SSL"); | |
sc.init(null, trustAllCerts, new java.security.SecureRandom()); | |
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); | |
URL url = new URL(_url); | |
java.lang.System.setProperty("https.protocols", "TLSv1.2"); | |
con = (HttpURLConnection) url.openConnection(); | |
con.setRequestMethod("GET"); | |
con.setDoInput(true); | |
con.setUseCaches(false); | |
con.setDefaultUseCaches(false); | |
con.setConnectTimeout(300000); // 300초 | |
con.setReadTimeout(300000); // 300초 | |
con.setRequestProperty("Content-Type", "application/json"); | |
con.setRequestProperty("Authorization", "Basic " + base64Creds); | |
in = new InputStreamReader((InputStream) con.getContent()); | |
br = new BufferedReader(in); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
} catch (Exception e) { | |
/* | |
* status 200 이 아닌 400~500 에러일 경우 에러 body에 따로 담겨온다. | |
*/ | |
try { | |
in = new InputStreamReader((InputStream) con.getErrorStream()); | |
br = new BufferedReader(in); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line).append("\n"); | |
} | |
} catch (Exception e2) { | |
} | |
logger.error(e); | |
} finally { | |
try { | |
if (os != null) { | |
os.flush(); | |
os.close(); | |
} | |
if (br != null) { | |
br.close(); | |
} | |
if (in != null) { | |
in.close(); | |
} | |
if (con != null) { | |
con.disconnect(); | |
} | |
} catch (Exception e) { | |
} | |
} | |
return sb.toString(); | |
} | |
/** | |
* 사용안함. | |
* HttpClient 로 시도할 경우 403 forbidden 에러 발생 | |
* | |
private HttpClient getHttpClient() throws Exception { | |
SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); | |
// set up a TrustManager that trusts everything | |
sslContext.init(null, new TrustManager[] { new X509TrustManager() { | |
public X509Certificate[] getAcceptedIssuers() { | |
System.out.println("getAcceptedIssuers ============="); | |
return null; | |
} | |
public void checkClientTrusted(X509Certificate[] certs, String authType) { | |
System.out.println("checkClientTrusted ============="); | |
} | |
public void checkServerTrusted(X509Certificate[] certs, String authType) { | |
System.out.println("checkServerTrusted ============="); | |
} | |
} }, new SecureRandom()); | |
SSLSocketFactory sf = new SSLSocketFactory(sslContext); | |
// javax.net.ssl.SSLException: hostname in certificate didn't match: <tourvis.zendesk.com> != <ssl385002.cloudflaressl.com> OR <ssl385002.cloudflaressl.com> OR <*.zdorigin.com> OR <zdorigin.com> | |
sf.setHostnameVerifier(new X509HostnameVerifier() { | |
@Override | |
public boolean verify(String arg0, SSLSession arg1) { | |
// TODO Auto-generated method stub | |
return true; | |
} | |
@Override | |
public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException { | |
// TODO Auto-generated method stub | |
} | |
@Override | |
public void verify(String arg0, X509Certificate arg1) throws SSLException { | |
// TODO Auto-generated method stub | |
} | |
@Override | |
public void verify(String arg0, SSLSocket arg1) throws IOException { | |
// TODO Auto-generated method stub | |
} | |
}); | |
Scheme httpsScheme = new Scheme("https", 443, sf); | |
SchemeRegistry schemeRegistry = new SchemeRegistry(); | |
schemeRegistry.register(httpsScheme); | |
// apache HttpClient version >4.2 should use BasicClientConnectionManager | |
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); | |
return new DefaultHttpClient(cm); | |
} | |
private String getHttpPOST2String(String url, String body) throws Exception { | |
HttpClient httpclient = getHttpClient(); | |
Map<String, String> headers = new HashMap<>(); | |
headers.put("content-type", "application/json"); | |
headers.put("Authorization", 문의토큰_AUTHORIZATION); | |
HttpPost post = new HttpPost(url); | |
if (headers != null && !headers.isEmpty()) { | |
for (String key : headers.keySet()) { | |
post.addHeader(key, headers.get(key)); | |
} | |
} | |
if (body != null) { | |
StringEntity params = new StringEntity(body, "UTF-8"); | |
post.setEntity(params); | |
} | |
HttpResponse response = httpclient.execute(post); | |
return EntityUtils.toString(response.getEntity(), "UTF-8"); | |
} | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment