83 lines
2.4 KiB
Java
83 lines
2.4 KiB
Java
package com.interplug.qcast.util;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.InputStreamReader;
|
|
import java.io.OutputStreamWriter;
|
|
import java.net.HttpURLConnection;
|
|
import java.net.URL;
|
|
import org.springframework.http.HttpMethod;
|
|
import org.springframework.stereotype.Component;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import lombok.RequiredArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
@Slf4j
|
|
@Component
|
|
@RequiredArgsConstructor
|
|
public class InterfaceQsp {
|
|
/**
|
|
* API Call
|
|
*
|
|
* @param apiPath
|
|
* @param requestObject
|
|
* @return String
|
|
* @throws Exception
|
|
*/
|
|
public String callApi(HttpMethod httpMethod, String apiPath, Object requestObject)
|
|
throws Exception {
|
|
|
|
URL url = null;
|
|
HttpURLConnection con = null;
|
|
OutputStreamWriter osw = null;
|
|
BufferedReader br = null;
|
|
StringBuilder sb = null;
|
|
|
|
try {
|
|
url = new URL(apiPath);
|
|
con = (HttpURLConnection) url.openConnection();
|
|
con.setConnectTimeout(5000); // 서버에 연결되는 Timeout 시간 설정
|
|
con.setReadTimeout(5000); // InputStream 읽어 오는 Timeout 시간 설정
|
|
con.setRequestMethod(httpMethod.toString());
|
|
con.setRequestProperty("Content-Type", "application/json");
|
|
con.setDoInput(true);
|
|
con.setUseCaches(false);
|
|
con.setDefaultUseCaches(false);
|
|
|
|
if (HttpMethod.GET.equals(httpMethod)) {
|
|
con.setDoOutput(false);
|
|
} else {
|
|
con.setDoOutput(true); // POST 데이터를 OutputStream으로 넘겨 주겠다는 설정
|
|
if (requestObject != null) {
|
|
ObjectMapper om = new ObjectMapper();
|
|
osw = new OutputStreamWriter(con.getOutputStream());
|
|
osw.write(om.writeValueAsString(requestObject)); // json 형식의 message 전달
|
|
osw.flush();
|
|
}
|
|
}
|
|
|
|
sb = new StringBuilder();
|
|
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
|
|
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
|
|
|
|
String line;
|
|
while ((line = br.readLine()) != null) {
|
|
sb.append(line);
|
|
}
|
|
}
|
|
} catch (Exception e) {
|
|
throw e;
|
|
} finally {
|
|
try {
|
|
if (osw != null)
|
|
osw.close();
|
|
if (br != null)
|
|
br.close();
|
|
} catch (Exception e) {
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
return sb != null ? sb.toString() : null;
|
|
}
|
|
}
|