포스트 목록

2016년 7월 6일 수요일

크로스 도메인 문제 해결

이 게시물은 참조하지 않는 것을 권장합니다.

Ajax 로 다른 도메인에 요청을 할 경우 크로스 도메인 이슈가 발생한다.

예를들어 Ajax 로 아래 사이트에 요청 하게될 경우 문제가 발생한다.

http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=596
(로또 596회차 번호를 Json으로 반환)

보안을 이유로 만들었다고는 하지만, 여간 불편한게 아니다.

그래서 이번에는 크로스 도메인 이슈를 해결하는 방법을 작성한다.

--------------------------------------------------------------------------------------------------

서버단에서 아래 로직을 작성한다.
(Controller Layer에서 처리하는 것으로 한다.)

1. 먼저 pom.xml 에 다음을 추가한다.



<dependency>
  <groupid>org.apache.httpcomponents</groupid>
  <artifactid>httpclient</artifactid>
  <version>4.5.2</version>
</dependency>


2. 아래 get 방식과 post 방식중 한가지를 선택하여 적용한다.

-- get 방식



StringBuilder sb = new StringBuilder();

CloseableHttpClient httpClient = HttpClients.createDefault();
// get 방식으로 요청
HttpGet httpGet = new HttpGet();
CloseableHttpResponse response = httpClient.execute(httpGet);

try{

  HttpEntity entity = response.getEntity("http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=596");
  if(entity != null) {

    BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));

    String line = "";
    while((line = br.readLine()) != null) {
      sb.append(line);
    }
  }
} catch(ClientProtocolException e) {
  logger.debug(e.getMessage());
} catch(IOException e) {
  logger.debug(e.getMessage());
} finally {
  response.close();
}

return sb.toString();



-- post 방식



StringBuilder sb = new StringBuilder();

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.naver.com");

// parameter 세팅
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("param1", "value1"));
nvps.add(new BasicNameValuePair("param2", "value2"));

try {
  httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

  CloseableHttpResponse response = httpClient.execute(httpPost);

  HttpEntity entity = response.getEntity();
  BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

  try {
    String line = "";
    while((line = br.readLine()) != null) {
      sb.append(line);
    }
  } finally {
    br.close();
    response.close();
  }
} catch(Exception e) {
  logger.debug("HttpClient Connection Exception :: " + e.getMessage());
}

return sb.toString();


3. 해당 값을 처리하면 된다.

댓글 없음:

댓글 쓰기