[JAVA] 특정 URL 헤더의 쿠키 가져오기 (getCookiesOnly)
특정 URL의 내용(responseBody)을 얻기 위해서는 일반적으로 자바에서 기본 제공하는 java.net.HttpURLConnection 클래스를 사용한다. 그런데 해당 클래스로는 응답코드가 301, 302일 경우(Location 으로 리다이렉트하는 경우)에는 Header 내의 Cookie 값들을 제대로 가져올 수 없었다.
대신 아래와 같이 GetMethod 클래스를 사용해보니 Cookie 값부터 Locaion 값까지 Header 내용을 잘 가져올 수 있었다.
1. 라이브러리 임포트
/WEB-INF/lib/ 경로에 commons-httpclient-3.1.jar, commons-logging-1.0.4.jar, commons-codec-1.10.jar 파일을 위치시키기
또는 pom.xml 에 아래 내용 입력
2. 특정 URL 의 쿠키 가져오기 예제
|
import java.io.IOException;
import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod;
public class GetMethodTest { public static void main(String[] args) { try { GetMethodTest instance = new GetMethodTest(); String cookies = instance.getCookiesOnly(“https://blog.naver.com/bb_”); System.out.println(“———-“); System.out.println(“cookies : ” + cookies); } catch (Exception e) { e.printStackTrace(); } } private String getCookiesOnly(String targetUrl) throws IOException, Exception { StringBuffer cookieBuff = new StringBuffer(); HttpClient httpClient = null; GetMethod getMethod = null; try { httpClient = new HttpClient(); getMethod = new GetMethod(targetUrl); getMethod.setFollowRedirects(false);
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
int statusCode = httpClient.executeMethod(getMethod);
Header[] headers = getMethod.getResponseHeaders(); if (headers != null && headers.length > 0) { int headerCount = headers.length; for (int i=0; i<headerCount; i++) { Header header = headers[i]; if (header == null) { continue; } if (header.getName() == null) { continue; } if (header.getValue() == null) { continue; } System.out.println(“header (” + i + “) : ” + header.getName() + ” : ” + header.getValue()); if (header.getName().equalsIgnoreCase(“Set-Cookie”)) { String oneCookie = header.getValue(); int idxSemicolon = oneCookie.indexOf(“;”); if (idxSemicolon > -1) { oneCookie = oneCookie.substring(0, idxSemicolon + 1); } // 빈값 세팅은 skip if (oneCookie.endsWith(“=\”\”;”) || oneCookie.endsWith(“=”;”)) { continue; } if (cookieBuff.length() > 0) { cookieBuff.append(” “); } cookieBuff.append(oneCookie); } } } System.out.println(“statusCode : ” + statusCode); // System.out.println(“responseBody : ” + getMethod.getResponseBodyAsString()); } catch (IOException e) { throw e;
} catch (Exception e) { throw e;
} finally { try { if (getMethod != null) { getMethod.releaseConnection(); } } catch (Exception e) { } finally { getMethod = null; }
httpClient = null; }
return cookieBuff.toString(); } }
|
3. 실행결과
|
header (0) : Date : Tue, 17 Nov 2020 03:21:02 GMT header (1) : Content-Type : text/html;charset=UTF-8 header (2) : Content-Length : 2671 header (3) : Connection : close header (4) : Vary : Accept-Encoding header (5) : Vary : Accept-Encoding header (6) : Cache-Control : no-cache header (7) : Expires : Thu, 01 Jan 1970 00:00:00 GMT header (8) : Set-Cookie : JSESSIONID=2E502B130F6A70B9A92D812644EFAAF7.jvm1; Path=/; Secure; HttpOnly header (9) : Server : nxfps header (10) : Referrer-policy : unsafe-url statusCode : 200 ———- cookies : JSESSIONID=2E502B130F6A70B9A92D812644EFAAF7.jvm1;
|
4. 쿠키의 활용 (특정 페이지의 내용 가져오기)
cookies 변수는 아래와 같은 형태를 갖는다.
name1=value1;name2=value2;name3=value3;
이렇게 얻은 쿠키를 세팅해서 특정 URL의 내용(responseBody)를 가져오기 위해서는 HttpURLConnection 클래스의 setRequestProperty 메서드를 사용하면 된다.
예를 들면 아래와 같다.
|
String strUrl = “https://blog.naver.com/bb_”; URL urlObj = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
(중략)
String cookies = “name1=value1;name2=value2;name3=value3;”; conn.setRequestProperty(“Cookie”, cookies);
(후략)
|
참고삼아 HttpURLConnection 클래스로 특정 URL의 내용(responseBody)를 가져오는 코드를 남겨둔다. (GET방식)
|
public String getResponseBody(String strUrl, String encoding, String cookies) throws IOException, Exception {
URL urlObj = null; HttpURLConnection conn = null; InputStreamReader isr = null; BufferedReader br = null; StringBuffer response = new StringBuffer();
try { urlObj = new URL(strUrl); conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty(“access-type”, “AJAX”); conn.setConnectTimeout(30 * 1000); conn.setReadTimeout(30 * 1000);
// 쿠키 세팅
if (cookies != null && cookies.length() > 0) { conn.setRequestProperty(“Cookie”, cookies); }
isr = new InputStreamReader(conn.getInputStream(), encoding); br = new BufferedReader(isr);
String oneLine = null; while ((oneLine = br.readLine()) != null) { response.append(oneLine); }
} catch (IOException e) { throw e;
} catch (Exception e) { throw e;
} finally { try { if (isr != null) { isr.close(); } } catch (IOException e) { } catch (Exception e) { } finally { isr = null; } try { if (br != null) { br.close(); } } catch (IOException e) { } catch (Exception e) { } finally { br = null; } try { if (conn != null) { conn.disconnect(); } } catch (NullPointerException e) { } catch (Exception e) { } finally { br = null; } } return response.toString(); }
|
5. 쿠키의 활용 (특정 페이지로 페이지 리다이렉트)
cookies 변수는 아래와 같은 형태를 갖는다.
name1=value1;name2=value2;name3=value3;
이렇게 얻은 쿠키를 세팅해서 특정 페이지를 열 수 있다.
우선 백엔드 단에서는 해당 쿠키를 어트리뷰트에 담아서(ex : pageContext.setAttribute(“pageCookies”, cookies);) 프론트엔드로 내려주고, 이후 자바스크립트 단에서 document.cookie 값을 바꾸고 location.href 로 페이지를 이동시키면 된다.
아래는 jsp 페이지 예제다.
|
<%@page language=”java” %> <%@page contentType=”text/html; charset=UTF-8″ %>
<html>
<script>
window.onload = function() {
// document.cookie = “name1=value1;name2=value2;name3=value3;”;
document.cookie = “${pageCookies}”;
location.href = “http://이동하기_원하는_특정_페이지“;
}
</script>
</html>
|