Java の Java.net.HttpCookie

前提条件 - クッキー

多くの Web サイトは、Cookie と呼ばれる小さなテキスト文字列を使用して、接続間でクライアント側の状態を永続的に保存します。 Cookie はサーバーからクライアントに渡され、リクエストと応答の HTTP ヘッダーに入れられて再び戻されます。サーバーは Cookie を使用して、セッション ID、ショッピング カートの内容、ログイン認証情報、ユーザー設定などを示すことができます。 HttpCookie オブジェクトは、サーバーとユーザー エージェントの間で状態情報を伝達する http Cookie を表します。 Cookie はステートフル セッションを作成するために広く採用されています。 http Cookie の仕様は 3 つあります。

HttpCookie クラスは、これら 3 つの形式の構文をすべて受け入れることができます。

コンストラクター:

指定された名前と値を持つ Cookie を作成します。名前には ASCII 英数字のみが含まれ、RFC 2965 に準拠する必要があります。名前が正しくない場合は IllegalArgument 例外がスローされ、名前が null の場合は NullPointerException がスローされます。値には、Cookie が保存したいものであれば何でもかまいません。

    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. 解析() : ヘッダー文字列から解析された Cookie のリストを返します。ヘッダーは set-cookie または set-cookie2 トークンで始まる必要があります。あるいは、トークンをまったく含めることはできません。
        Syntax :     public static List parse(String header)   
    Parameters :
    header : String to be parsed as cookies
  2. hasExpired() : Cookie の有効期限が切れているかどうかを示すブール値を返します。
        Syntax :     public boolean hasExpired()  
  3. setComment() : Cookie の目的を説明する短い説明を設定するために使用されます。ユーザーに Cookie を提示するときに使用されます。
        Syntax :     public void setComment(String purpose)   
    Parameters :
    purpose : purpose of cookie
  4. getComment() : Cookie の説明を返すか、Cookie にコメントがない場合は null を返します。
        Syntax :     public void getComment()  
  5. setCommentURL() : Cookie の目的を説明する短いコメント URL を設定するために使用されます。ブラウザがユーザーに Cookie を提示するときに使用されます。
        Syntax :     public void setCommentURL(String purpose)   
    Parameters :
    purpose : purpose of cookie
  6. getCommentURL() : Cookie の URL コメントを返すか、Cookie に URL コメントがない場合は null を返します。
        Syntax :     public String getComment()  
  7. setDiscard() : ユーザー エージェントがこの Cookie を破棄するかどうかを設定するために使用されます。
        Syntax :     public void setDiscard(Boolean discard)   
    Parameters :
    discard : true if UA should discard otherwise false
  8. getDiscard() : setDiscard() メソッドで設定された破棄変数の状態を返します。より具体的には、UA がこの Cookie を破棄する場合は true を返し、それ以外の場合は false を返します。
        Syntax :     public Boolean getDiscard()  
  9. setPortList() : この Cookie が使用できるポートを指定するために使用されます。
        Syntax :     public void setPortList(String portList)   
    Parameters :
    portList : String of comma separated digits specifying the ports.
  10. getPortList() : この Cookie が使用できるポートのリストを返します。
        Syntax :     public String getPortList()  
  11. setDomain() : この Cookie が表示されるドメインを指定します。たとえば、bali.vacations.com のサーブレットから送信された Cookie は、通常、ブラウザによって queensland.vacations.com のページに返されません。サイトがこれを実現したい場合は、サーブレットで cookie.setDomain(.vacations.com) を指定できます。サーバーがドメイン外のホストに適用される Cookie を設定しないようにするには、指定されたドメインが次の要件を満たしている必要があります: ドットで始まる必要があります (例: .coreservlets.com)。
        Syntax :     public void setDomain(String domain)   
    Parameters :
    domain : String representing the domain in which this cookie is visible
  12. getDomain() : この Cookie が表示されるドメインを返します。
        Syntax :     public String getDomain()  
  13. setMaxAge() : Cookie の最大存続期間を秒単位で設定するために使用されます。 Cookie が作成されてから存続する最大時間を指定します。負の値は、ブラウザが終了するとすぐに Cookie が期限切れになることを指定します。
        Syntax :     public void setMaxAge(long age)   
    Parameters :
    age : Max survive time in seconds
  14. getMaxAge() : Cookie の最大存続期間を返します。
        Syntax :     public long getMaxAge()  
  15. setPath() : Cookie を返すクライアントへのパスを指定するために使用されます。この Cookie は、指定されたパスのすべてのページとサブディレクトリに表示されます。たとえば、サーバーが http://ecommerce.site.com/toys/specials.html から Cookie を送信した場合、ブラウザは http://ecommerce.site.com/to/beginners.html に接続するときに Cookie を送り返しますが、http://ecommerce.site.com/c/classic.html には送り返しません。
        Syntax :     public void setPath(String uri)   
    Parameters :
    uri - a String specifying a path
  16. getPath() : この Cookie に設定されたパスを返します。
        Syntax :     public String getPath()  
  17. Javaの実装:
  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() : この Cookie の送信中に安全なプロトコルを使用するかどうかを示します。デフォルト値は false です。
        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() : この Cookie を安全なプロトコルで送信する必要がある場合は true を返し、それ以外の場合は false を返します。
        Syntax :     public boolean getSecure()  
  23. getName() : クッキーの名前を返します。
           Syntax :     public String getName()  
  24. setValue() : 初期化後に Cookie に新しい値を割り当てます。
        Syntax :     public void setValue(String newValue)   
    Parameters :
    newValue - a String specifying the new value
  25. getValue : Cookieの値を返します。
        Syntax :     public String getValue()  
  26. getVersion() : Cookie が元の Netscape 仕様に準拠している場合は 0 を返します。 Cookie が RFC 2965/2109 に準拠している場合は 1
        Syntax :     public int getVersion()  
  27. setVersion() : この Cookie が使用する Cookie プロトコルのバージョンを設定するために使用されます。
        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() : Cookie が http でのみ使用できる場合、つまり JS vb などのスクリプト言語では使用できない場合は true を返します。
        Syntax :     public boolean isHttpOnly()  
  29. setHttpOnly() : この Cookie が 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() : この Cookie の文字列表現を構築します。
           Syntax :    public String toString()  
  32. 等しい() : 2 つの http Cookie が互いに等しい場合は true を返し、それ以外の場合は false を返します。
           Syntax :    public boolean equals(Object obj)  
  33. ハッシュコード() : この http Cookie のハッシュ コードを返します。結果は、この Cookie の 3 つの重要なコンポーネント (名前ドメインとパス) のハッシュ コード値の合計です。クラス Object の hashCode をオーバーライドします。
        Syntax :     public int hashCode()  
  34. クローン() : このオブジェクトのコピーを作成して返します。オブジェクトクラスの clone メソッドをオーバーライドします。
        Syntax :     public Object clone()  

Javaの実装:

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

Web サーバーで Cookie が実際にどのように使用されるかを示す別の例では、www.facebook.com によって保存されている Cookie の詳細を出力します。

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 ドキュメント

クイズの作成