본문 바로가기

WEB개발

웹페이지에서 외부 json response 시 크로스도메인 해결 방법

728x90
반응형

- 웹페이지 UI에서 외부 도메인을 통하여 json response 진행 시
   보안정책 공통규격이 위배되는 크로스도메인 이슈 발생
- java 내부 서버단에서 HttpURLConnection 를 통하여 문제 해결
※ 크롬의 경우 크롬 자체적으로 크로스도메인 허용 보안정책을 설정해 주는
    구글어플리케이션을 설치하면 UI에서 외부 json call 해결 가능, (IE는 미지원)

[우회 방법]
1) UI (예제 : jquery)
- json post 방식으로 java 클래스 부르기
var param = "id=" + strLoginID + "&pass=" + pwSha512;
var url      = "/TMSYS030/jsonPostCross_uPcRecodeList.action"; // java 클래스
jQuery.post(url, param, function(data){
    ...
}

2) java 서버단 (예제 : 외부 json call url, HttpURLConnection으로 크로스도메인 보안정책 허용)
public Map jsonPostCross_uPcRecodeList(Map model) throws Exception {
     Map map = new HashMap();
     try{
         String paramId      = (String) model.get("id");
         String paramPass = (String) model.get("pass");
         String body          = "id="+paramId+"&pass="+paramPass;
         URL url               = new URL("https://centrex.uplus.co.kr/RestApi/recordlist"); // 외부 json call

         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("POST");
         connection.setDoInput(true);
         connection.setDoOutput(true);
         connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

         OutputStream os = connection.getOutputStream();
         os.write( body.getBytes("euc-kr") );
         os.flush();
         os.close();

         BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream()));
         StringBuffer buffer = new StringBuffer();

            int read = 0;
            char[] cbuff = new char[1024]; 
            while ((read = reader.read(cbuff)) > 0){
               buffer.append(cbuff, 0, read);
            }
           
         reader.close();
         map.put("DS", buffer.toString());
        } catch(Exception e){
         map.put("DS", "ERR");
        }
     return map;
 }

728x90
반응형