-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpUrlConnection.java
More file actions
431 lines (353 loc) · 11.9 KB
/
HttpUrlConnection.java
File metadata and controls
431 lines (353 loc) · 11.9 KB
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
package egovframework.system.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUrlConnection {
private static final Logger logger = LoggerFactory.getLogger(HttpUrlConnection.class);
/**
*
* @Method Name : xmlSend
* @Method 설명 : 일반적인 xmlSend 기능. 결과값 인코딩 설정 추가
*
* @param paramMap
* @param url
* @param parseCharsetName
* @return
*/
public static String xmlSend(HashMap paramMap, String url, String parseCharsetName) {
String baseUrl = url;
String parameters = "";
String result = "";
Set<String> keySet = paramMap.keySet();
Iterator<String> keys = keySet.iterator();
while (keys.hasNext()) {
String paramKey = keys.next();
String paramValue = (String)paramMap.get(paramKey);
if (parameters.equals("")) {
parameters += paramKey + "=" + paramValue;
} else {
parameters += "&" + paramKey + "=" + paramValue;
}
}
if (logger.isDebugEnabled()) {
logger.debug(String.format("url[%s]", baseUrl));
logger.debug(String.format("params[%s]", parameters));
}
OutputStream out = null;
BufferedReader reader = null;
StringBuffer buf = new StringBuffer();
try {
URL targetURL = new URL(baseUrl);
URLConnection urlConn = targetURL.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) urlConn;
httpConnection.setConnectTimeout(30000); //서버통신 timeout 설정.
httpConnection.setReadTimeout(30000); //스트림읽기 timeout 설정.
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setUseCaches(false);
httpConnection.setDefaultUseCaches(false);
out = httpConnection.getOutputStream();
out.write(parameters.getBytes("utf-8"));
out.flush();
out.close();
reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), parseCharsetName));
// result = reader.readLine();
int c;
while ((c = reader.read()) != -1) {
buf.append((char)c);
}
result = buf.toString();
reader.close();
//logger.debug("result = " + result);
} catch (IOException e) {
System.out.println("xmlSend fail");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("xmlSend fail");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("xmlSend fail");
}
}
}
return result;
}
public static String requestHttpGetJson(String url, String authkey) {
String baseUrl = url;
String result = "";
OutputStream out = null;
BufferedReader reader = null;
StringBuffer buf = new StringBuffer();
HttpURLConnection httpConnection = null;
if (logger.isDebugEnabled()) {
logger.debug(String.format("url[%s]", baseUrl));
}
try {
URL targetURL = new URL(baseUrl);
URLConnection urlConn = targetURL.openConnection();
httpConnection = (HttpURLConnection) urlConn;
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Content-Type", "application/json");
// 일부 API 사용 시 인증 필요없음.
if (StringUtil.hasText(authkey)) {
httpConnection.setRequestProperty("Authorization", "Basic " + authkey);
}
httpConnection.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "utf-8"));
int c;
while ((c = reader.read()) != -1) {
buf.append((char)c);
}
result = buf.toString();
reader.close();
} catch (IOException e) {
//e.printStackTrace();
try {
if ( httpConnection.getErrorStream() != null ) {
BufferedReader error = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream(), "utf-8"));
int c;
while ((c = error.read()) != -1) {
buf.append((char)c);
}
error.close();
logger.info("### requestHttpGetJson Exception : " + buf.toString());
}
} catch (IOException ee) {
System.out.println("requestHttpGetJson fail");
}
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("requestHttpGetJson fail");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("requestHttpGetJson fail");
}
}
}
return result;
}
public String requestHttpPostJson(String url, ParamMap headerparams, JSONObject jsonparams) throws Exception{
String logPrefix = "REQ_HTTP_POST_JSON";
logger.info("{} into method.", logPrefix);
logger.debug("{} url = '{}'", logPrefix, url);
logger.debug("{} headerparams = '{}'", logPrefix, headerparams);
logger.debug("{} jsonparams = '{}'", logPrefix, jsonparams);
String baseUrl = url;
String result = "";
OutputStream out = null;
BufferedReader reader = null;
StringBuffer buf = new StringBuffer();
HttpURLConnection httpConnection = null;
try {
URL targetURL = new URL(baseUrl);
ignoreSsl();
URLConnection urlConn = targetURL.openConnection();
httpConnection = (HttpURLConnection) urlConn;
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Content-Type", "application/json");
if (StringUtil.hasText(headerparams.getStr("authkey"))) {
httpConnection.setRequestProperty("Authorization", headerparams.getStr("authkey"));
}
if (StringUtil.hasText(headerparams.getStr("clientId"))) {
httpConnection.setRequestProperty("X-IB-Client-Id", headerparams.getStr("clientId"));
}
if (StringUtil.hasText(headerparams.getStr("clientPw"))) {
httpConnection.setRequestProperty("X-IB-Client-Passwd", headerparams.getStr("clientPw"));
}
httpConnection.setRequestMethod("POST");
out = httpConnection.getOutputStream();
out.write(jsonparams.toJSONString().getBytes("utf-8"));
out.flush();
InputStream inputStream = httpConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
reader = new BufferedReader(inputStreamReader);
int c;
while ((c = reader.read()) != -1) {
buf.append((char)c);
}
result = buf.toString();
reader.close();
} catch (MalformedURLException e) {
System.out.println("requestHttpPostJson fail");
} catch (ProtocolException e) {
System.out.println("requestHttpPostJson fail");
} catch (UnsupportedEncodingException e) {
System.out.println("requestHttpPostJson fail");
} catch (IOException e) {
logger.error("{} Exception Handled. message = {}", logPrefix, e.getMessage());
try {
BufferedReader error = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream(), "utf-8"));
int c;
while ((c = error.read()) != -1) {
buf.append((char)c);
}
error.close();
logger.info("### requestHttpPostJson Exception : " + buf.toString());
} catch (IOException ee) {
System.out.println("requestHttpPostJson fail");
}
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("requestHttpPostJson fail");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("requestHttpPostJson fail");
}
}
}
return result;
}
public String requestHttpPutJson(String url, ParamMap headerparams, JSONObject jsonparams) {
String baseUrl = url;
String result = "";
OutputStream out = null;
BufferedReader reader = null;
StringBuffer buf = new StringBuffer();
HttpURLConnection httpConnection = null;
if (logger.isDebugEnabled()) {
logger.debug(String.format("url[%s]", baseUrl));
logger.debug(String.format("header[%s]", headerparams));
logger.debug(String.format("params[%s]", jsonparams.toJSONString()));
}
try {
URL targetURL = new URL(baseUrl);
URLConnection urlConn = targetURL.openConnection();
httpConnection = (HttpURLConnection) urlConn;
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestProperty("Authorization", headerparams.getStr("authkey"));
httpConnection.setRequestMethod("PUT");
out = httpConnection.getOutputStream();
out.write(jsonparams.toJSONString().getBytes("utf-8"));
out.flush();
reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "utf-8"));
int c;
while ((c = reader.read()) != -1) {
buf.append((char)c);
}
result = buf.toString();
reader.close();
} catch (MalformedURLException e) {
System.out.println("requestHttpPutJson fail");
} catch (ProtocolException e) {
System.out.println("requestHttpPutJson fail");
} catch (UnsupportedEncodingException e) {
System.out.println("requestHttpPutJson fail");
} catch (IOException e) {
try {
BufferedReader error = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream(), "utf-8"));
int c;
if(error != null) {
while ((c = error.read()) != -1) {
buf.append((char)c);
}
error.close();
}
logger.info("### requestHttpPutJson Exception : " + buf.toString());
} catch (IOException ee) {
System.out.println("requestHttpPutJson fail");
}
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("requestHttpPutJson fail");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("requestHttpPutJson fail");
}
}
}
return result;
}
public void ignoreSsl() throws Exception{
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
private void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
class miTM implements TrustManager,X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
}