[Java] 컨트롤러에서 open api 호출하기
2022. 12. 12. 08:45ㆍProgram/Java
CORS 에러를 해결하기 위해 JSP문서에서 open api를 호출하는 대신,
컨트롤러에서 공공기관의 open api를 대신 호출시키고 데이터를 받아오는 방법을 사용했다
corsCatch.java
@RequestMapping(value = "/test", method = { RequestMethod.POST },produces = "application/text; charset=utf8")
public String test1(@RequestParam("url") String preurl) throws IOException {
String preurl = preurl.replaceAll("&", "&"); //&로 넘어온 &를 치환
String result = null;
URL url = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
url = new URL(preurl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(2000);
inputStream = (InputStream) urlConnection.getContent();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buff = new StringBuffer();
String oneLine = null;
while ((oneLine = bufferedReader.readLine()) != null) {
if (oneLine == null || oneLine.length() == 0) {
continue;
}
buff.append(oneLine);
}
return buff.toString();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (NullPointerException e) {
} catch (Exception e) {
} finally {
bufferedReader = null;
}
try {
if (inputStreamReader != null) {
inputStreamReader.close();
}
} catch (NullPointerException e) {
} catch (Exception e) {
} finally {
inputStreamReader = null;
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (NullPointerException e) {
} catch (Exception e) {
} finally {
inputStream = null;
}
try {
if (urlConnection != null) {
urlConnection.disconnect();
}
} catch (NullPointerException e) {
} catch (Exception e) {
} finally {
urlConnection = null;
}
}
return result;
}
urlConnection을 사용해 호출하고 한글이 깨져서 InputStreamReader에 UTF-8을 설정해주었다.
corsInfo.jsp
var url = "" //호출할 url
$.ajax({
url : "test",
data :{
url:url
},
type :"post",
dataType : "xml",
success : function(data) {
console.log(data);
var obj = xmlToJson(data);
console.log(obj);
},
error : function(err) {
alert(err.status);
}
});
dataType을 xml로 가져와서 Json파일로 변환하였다