Java의 Java.net.HttpCookie

전제조건 - 쿠키

많은 웹사이트에서는 쿠키라고 하는 작은 텍스트 문자열을 사용하여 연결 간에 지속적인 클라이언트측 상태를 저장합니다. 쿠키는 서버에서 클라이언트로 전달되고 요청 및 응답의 HTTP 헤더를 통해 다시 전달됩니다. 쿠키는 서버에서 세션 ID, 장바구니 콘텐츠, 로그인 자격 증명, 사용자 기본 설정 등을 나타내는 데 사용될 수 있습니다. HttpCookie 객체는 서버와 사용자 에이전트 간에 상태 정보를 전달하는 http 쿠키를 나타냅니다. 쿠키는 상태 저장 세션을 생성하기 위해 널리 채택됩니다. http 쿠키 사양에는 3가지가 있습니다.

HttpCookie 클래스는 이 세 가지 형태의 구문을 모두 허용할 수 있습니다.

생성자 :

지정된 이름과 값을 가진 쿠키를 생성합니다. 이름은 ASCII 영숫자 문자만 포함해야 하며 RFC 2965를 준수해야 합니다. 이름이 올바르지 않으면 IllegalArgument 예외가 발생하고 이름이 null이면 NullPointerException이 발생합니다. 값은 쿠키가 저장하고 싶은 모든 것이 될 수 있습니다.

    Syntax :     public HttpCookie(String name   
String value)
Parameters :
name : name of cookie
value : value of cookie
Throws :
IllegalArgumentException : if name does not conform to RFC2965
NullPointerException : if name is null

방법:

  1. 구문 분석(): 헤더 문자열에서 구문 분석된 쿠키 목록을 반환합니다. 헤더는 set-cookie 또는 set-cookie2 토큰으로 시작하거나 토큰을 전혀 포함해서는 안 됩니다.
        Syntax :     public static List parse(String header)   
    Parameters :
    header : String to be parsed as cookies
  2. 만료됨(): 쿠키가 만료되었는지 여부를 나타내는 부울 값을 반환합니다.
        Syntax :     public boolean hasExpired()  
  3. setComment() : 쿠키의 목적을 설명하는 간단한 설명을 설정하는 데 사용됩니다. 사용자에게 쿠키를 제공할 때 사용됩니다.
        Syntax :     public void setComment(String purpose)   
    Parameters :
    purpose : purpose of cookie
  4. getComment() : 쿠키에 대한 설명을 반환하거나 쿠키에 설명이 없으면 null을 반환합니다.
        Syntax :     public void getComment()  
  5. setCommentURL() : 쿠키의 목적을 설명하는 짧은 설명 URL을 설정하는 데 사용됩니다. 브라우저가 사용자에게 쿠키를 제공할 때 사용됩니다.
        Syntax :     public void setCommentURL(String purpose)   
    Parameters :
    purpose : purpose of cookie
  6. getCommentURL() : 쿠키의 URL 설명을 반환하거나, 쿠키에 URL 설명이 없으면 null을 반환합니다.
        Syntax :     public String getComment()  
  7. setDiscard() : 사용자 에이전트가 이 쿠키를 삭제해야 하는지 여부를 설정하는 데 사용됩니다.
        Syntax :     public void setDiscard(Boolean discard)   
    Parameters :
    discard : true if UA should discard otherwise false
  8. getDiscard() : setDiscard() 메소드에 의해 설정된 폐기 변수의 상태를 반환합니다. 더 구체적으로 말하면 UA가 이 쿠키를 삭제하면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
        Syntax :     public Boolean getDiscard()  
  9. setPortList() : 이 쿠키가 사용할 수 있는 포트를 지정하는 데 사용됩니다.
        Syntax :     public void setPortList(String portList)   
    Parameters :
    portList : String of comma separated digits specifying the ports.
  10. getPortList() : 이 쿠키가 사용할 수 있는 포트 목록을 반환합니다.
        Syntax :     public String getPortList()  
  11. setDomain() : 이 쿠키가 표시되어야 하는 도메인을 지정하세요. 예를 들어 bali.vacations.com의 서블릿에서 전송된 쿠키는 일반적으로 브라우저에 의해 queensland.vacations.com의 페이지로 반환되지 않습니다. 사이트에서 이를 원할 경우 서블릿은 cookie.setDomain(.vacations.com)을 지정할 수 있습니다. 서버가 도메인 외부의 호스트에 적용되는 쿠키를 설정하지 못하도록 하려면 지정된 도메인이 다음 요구 사항을 충족해야 합니다. 점으로 시작해야 합니다(예: .coreservlets.com).
        Syntax :     public void setDomain(String domain)   
    Parameters :
    domain : String representing the domain in which this cookie is visible
  12. getDomain() : 이 쿠키가 표시되는 도메인을 반환합니다.
        Syntax :     public String getDomain()  
  13. setMaxAge() : 쿠키의 최대 수명을 초 단위로 설정하는 데 사용됩니다. 쿠키가 생성된 후 쿠키가 살아있는 최대 시간을 지정합니다. 음수 값은 브라우저가 종료되자마자 쿠키가 만료되도록 지정합니다.
        Syntax :     public void setMaxAge(long age)   
    Parameters :
    age : Max survive time in seconds
  14. getMaxAge() : 쿠키의 최대 수명을 반환합니다.
        Syntax :     public long getMaxAge()  
  15. 세트패스() : 쿠키를 반환해야 하는 클라이언트의 경로를 지정하는 데 사용됩니다. 이 쿠키는 지정된 경로의 모든 페이지와 하위 디렉터리에 표시됩니다. 예를 들어 서버가 http://ecommerce.site.com/toys/specials.html에서 쿠키를 보낸 경우 브라우저는 http://ecommerce.site.com/to/beginners.html에 연결할 때 쿠키를 다시 보내지만 http://ecommerce.site.com/c/classic.html에는 연결할 수 없습니다.
        Syntax :     public void setPath(String uri)   
    Parameters :
    uri - a String specifying a path
  16. getPath() : 이 쿠키에 설정된 경로를 반환합니다.
        Syntax :     public String getPath()  
  17. 자바 구현:
  18. Java
       // Java Program to illustrate various   // methods of java.net.HttpCookie class   public     class   httpcookie1      {      public     static     void     main  (  String  []     args  )         {      // Constructor to create a new cookie.      HttpCookie     cookie     =     new     HttpCookie  (  'First'       '1'  );      // setComment() method      cookie  .  setComment  (  'Just for explanation'  );      // getComment() method      System  .  out  .  println  (  'Comment : '     +     cookie  .  getComment  ());      // setCommentURL() method      cookie  .  setCommentURL  (  '192.168.1.1'  );      // getCommentURL() method      System  .  out  .  println  (  'CommentURL : '     +     cookie  .  getCommentURL  ());      // setDiscard() method      cookie  .  setDiscard  (  true  );      // getDiscard() method      System  .  out  .  println  (  'Discard : '     +     cookie  .  getDiscard  ());      // setPortlist() method      cookie  .  setPortlist  (  '10018520'  );      // getPortList() method      System  .  out  .  println  (  'Ports: '     +     cookie  .  getPortlist  ());      // setDomain() method      cookie  .  setDomain  (  '.localhost.com'  );      // getDomain() method      System  .  out  .  println  (  'Domain : '     +     cookie  .  getDomain  ());      // setMaxAge() method      cookie  .  setMaxAge  (  3600  );      // getMaxAge() method      System  .  out  .  println  (  'Max Age : '     +     cookie  .  getMaxAge  ());      // setPath() method      cookie  .  setPath  (  '192.168.1.1/admin/index.html'  );      // getPath() method      System  .  out  .  println  (  'Path: '     +     cookie  .  getPath  ());      }   }   
  19. 산출
  20.  Comment : Just for explanation   
    CommentURL : 192.168.1.1
    Discard : true
    Ports: 10018520
    Domain : .localhost.com
    Max Age : 3600
    Path: 192.168.1.1/admin/index.html
  21. setSecure() : 이 쿠키를 보내는 동안 보안 프로토콜을 사용할지 여부를 나타냅니다. 기본값은 거짓입니다.
        Syntax :     public void setSecure(boolean secure)   
    Parameters:
    secure - If true the cookie can only be sent over a secure protocol like https.
    If false it can be sent over any protocol.
  22. getSecure() : 이 쿠키가 보안 프로토콜에 의해 전송되어야 하는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.
        Syntax :     public boolean getSecure()  
  23. getName() : 쿠키의 이름을 반환합니다.
           Syntax :     public String getName()  
  24. 설정값(): 초기화 후 쿠키에 새 값을 할당합니다.
        Syntax :     public void setValue(String newValue)   
    Parameters :
    newValue - a String specifying the new value
  25. getValue : 쿠키의 값을 반환합니다.
        Syntax :     public String getValue()  
  26. getVersion() : 쿠키가 원래 Netscape 사양을 준수하는 경우 0을 반환합니다. 쿠키가 RFC 2965/2109를 준수하는 경우 1
        Syntax :     public int getVersion()  
  27. 세트버전(): 이 쿠키가 사용하는 쿠키 프로토콜의 버전을 설정하는 데 사용됩니다.
        Syntax :    public void setVersion(int v)   
    throws IllegalArgumentException
    Parameters :
    v - 0 for original Netscape specification; 1 for RFC 2965/2109
    Throws :
    IllegalArgumentException - if v is neither 0 nor 1
  28. isHttpOnly() : 쿠키가 http에서만 사용될 수 있으면 true를 반환합니다. 즉, JS vb 등과 같은 스크립팅 언어에서는 사용할 수 없습니다.
        Syntax :     public boolean isHttpOnly()  
  29. setHttpOnly() : 이 쿠키가 http 전용인지 여부를 설정하는 데 사용됩니다.
        Syntax :     public void setHttpOnly(boolean httpOnly)   
    Parameters :
    httpOnly - if true make the cookie HTTP only i.e. only visible as part
    of an HTTP request.
  30. domainMatches() : 호스트 이름이 도메인에 있는지 확인하는 유틸리티 기능입니다.
        Syntax :     public static boolean domainMatches(String domain   
    String host)
    Parameters :
    domain : domain to check hostname with
    host : host to check
  31. toString() : 이 쿠키의 문자열 표현을 구성합니다.
           Syntax :    public String toString()  
  32. 같음() : 두 개의 http 쿠키가 서로 같으면 true를 반환하고 그렇지 않으면 false를 반환합니다.
           Syntax :    public boolean equals(Object obj)  
  33. 해시코드(): 이 http 쿠키의 해시 코드를 반환합니다. 결과는 이 쿠키의 세 가지 중요한 구성 요소인 이름 도메인과 경로의 해시 코드 값의 합계입니다. Object 클래스의 hashCode를 재정의합니다.
        Syntax :     public int hashCode()  
  34. 클론() : 이 객체의 복사본을 만들고 반환합니다. 개체 클래스의 복제 메서드를 재정의합니다.
        Syntax :     public Object clone()  

자바 구현:

Java
   // Java Program to illustrate various   // methods of java.net.HttpCookie class   import     java.net.HttpCookie  ;   public     class   httpcookie1      {      public     static     void     main  (  String  []     args  )         {      // Constructor to create a new cookie.      HttpCookie     cookie     =     new     HttpCookie  (  'First'       '1'  );      // setSecure() method      cookie  .  setSecure  (  true  );      // getSecure() method      System  .  out  .  println  (  'Secure : '     +     cookie  .  getSecure  ());      // getName() method      System  .  out  .  println  (  'Name : '     +     cookie  .  getName  ());      // setValue() method : can be used to modify value of cookie.      cookie  .  setValue  (  '2'  );      // getvalue() method      System  .  out  .  println  (  'Value : '     +     cookie  .  getValue  ());      // setVersion() method      cookie  .  setVersion  (  1  );      // getVersion() method      System  .  out  .  println  (  'Version : '     +     cookie  .  getVersion  ());      // setHttPonly() method      cookie  .  setHttpOnly  (  true  );      // isHttpOnly() method      System  .  out  .  println  (  'is HTTP only : '     +     cookie  .  isHttpOnly  ());      // toString() method      System  .  out  .  println  (  'toString : '     +     cookie  .  toString  ());      // hashcode() method      System  .  out  .  println  (  'Hashcode : '     +     cookie  .  hashCode  ());      }   }   

출력 :

 Secure : true   
Name : First
Value : 2
Version : 1
is HTTP only : true
toString : First='2'
Hashcode : 97440432

www.facebook.com에 저장된 쿠키의 세부 정보를 인쇄하는 웹 서버에서 쿠키가 실제로 어떻게 사용되는지 보여주는 또 다른 예

Java
   import     java.io.IOException  ;   import     java.net.CookieHandler  ;   import     java.net.CookieManager  ;   import     java.net.CookieStore  ;   import     java.net.HttpCookie  ;   import     java.net.URL  ;   import     java.net.URLConnection  ;   import     java.util.List  ;   public     class   httpcookie1      {      public     static     void     main  (  String  []     args  )     throws     IOException         {      String     urlString     =     'https://www.facebook.com/'  ;      // Create a default system-wide CookieManager      CookieManager     cookieManager     =     new     CookieManager  ();      CookieHandler  .  setDefault  (  cookieManager  );      // Open a connection for the given URL      URL     url     =     new     URL  (  urlString  );      URLConnection     urlConnection     =     url  .  openConnection  ();      urlConnection  .  getContent  ();      // Get CookieStore which is the default internal in-memory      CookieStore     cookieStore     =     cookieManager  .  getCookieStore  ();      // Retrieve all stored HttpCookies from CookieStore      List   <  HttpCookie  >     cookies     =     cookieStore  .  getCookies  ();      int     cookieIdx     =     0  ;      // Iterate HttpCookie object      for     (  HttpCookie     ck     :     cookies  )     {      System  .  out  .  println  (  '------ Cookie.'     +     ++  cookieIdx     +     ' -------'  );      // Get the cookie name      System  .  out  .  println  (  'Cookie name: '     +     ck  .  getName  ());      // Get the domain set for the cookie      System  .  out  .  println  (  'Domain: '     +     ck  .  getDomain  ());      // Get the max age of the cookie      System  .  out  .  println  (  'Max age: '     +     ck  .  getMaxAge  ());      // Get the path of the server      System  .  out  .  println  (  'Server path: '     +     ck  .  getPath  ());      // Get boolean if the cookie is being restricted to a secure      // protocol      System  .  out  .  println  (  'Is secured: '     +     ck  .  getSecure  ());      // Gets the value of the cookie      System  .  out  .  println  (  'Cookie value: '     +     ck  .  getValue  ());      // Gets the version of the protocol with which the given cookie is      // related.      System  .  out  .  println  (  'Cookie protocol version: '     +     ck  .  getVersion  ());      }      }   }   

출력 :

 ------------------ Cookie.1 ------------------   
Cookie name: fr
Domain: .facebook.com
Max age: 7775999
Server path: /
Is secured: true
Cookie value: 0Xj7tBSsWlmtXPo92..BZFC8G.qC.AAA.0.0.BZFC8G.AWUwiIgM
Cookie protocol version: 0

참조:

공식 Java 문서

퀴즈 만들기