Java.net.HttpCookie Javassa

Edellytys - Evästeet

Monet verkkosivustot käyttävät pieniä tekstijonoja, joita kutsutaan evästeiksi, tallentaakseen jatkuvan asiakaspuolen tilan yhteyksien välillä. Evästeet välitetään palvelimelta asiakkaalle ja takaisin pyyntöjen ja vastausten HTTP-otsikoissa. Palvelin voi käyttää evästeitä ilmoittamaan istuntotunnukset ostoskorin sisällöt kirjautumistiedot käyttäjäasetukset ja paljon muuta. HttpCookie-objekti edustaa http-evästettä, joka kuljettaa tilatietoja palvelimen ja käyttäjäagentin välillä. Eväste on laajalti käytössä tilallisten istuntojen luomiseen. http-evästemäärityksiä on kolme:

HttpCookie-luokka voi hyväksyä kaikki nämä 3 syntaksin muotoa.

Rakentaja:

Luo evästeen määritetyllä nimellä ja arvolla. Nimessä saa olla vain ASCII-aakkosnumeerisia merkkejä ja se on RFC 2965:n mukainen. Se heittää IllegalArgument-poikkeuksen, jos nimi ei ole oikea, tai NullPointerExceptionin, jos nimi on tyhjä. Arvo voi olla mitä tahansa evästettä, jonka haluat tallentaa.

    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

Menetelmät:

  1. parse() : palauttaa luettelon evästeistä, jotka on jäsennetty otsikkomerkkijonosta. otsikon täytyy alkaa sanoilla set-cookie tai set-cookie2 token, tai se ei saa sisältää lainkaan oikeutta.
        Syntax :     public static List parse(String header)   
    Parameters :
    header : String to be parsed as cookies
  2. on vanhentunut() : palauttaa loogisen arvon, joka osoittaa, onko eväste vanhentunut vai ei.
        Syntax :     public boolean hasExpired()  
  3. setComment() : Käytetään asettamaan lyhyt kuvaus, joka kuvaa evästeen tarkoitusta. Sitä käytetään, kun eväste esitetään käyttäjälle.
        Syntax :     public void setComment(String purpose)   
    Parameters :
    purpose : purpose of cookie
  4. getComment() : Palauttaa evästeen kuvauksen tai tyhjän, jos evästeellä ei ole kommentteja.
        Syntax :     public void getComment()  
  5. setCommentURL() : Käytetään määrittämään lyhyt kommentin URL-osoite, joka kuvaa evästeen tarkoitusta. Sitä käytetään, kun selain esittää evästeen käyttäjälle.
        Syntax :     public void setCommentURL(String purpose)   
    Parameters :
    purpose : purpose of cookie
  6. getCommentURL() : Palauttaa evästeen URL-kommentin tai tyhjän, jos evästeellä ei ole URL-kommentteja.
        Syntax :     public String getComment()  
  7. setDiscard() : Käytetään määrittämään, tuleeko käyttäjäagentin hylätä tämä eväste vai ei.
        Syntax :     public void setDiscard(Boolean discard)   
    Parameters :
    discard : true if UA should discard otherwise false
  8. getDiscard() : Palauttaa setDiscard()-metodilla asetetun hylkäämismuuttujan tilan. Tarkemmin sanottuna palauttaa tosi, jos UA hylkää tämän evästeen, muuten epätosi.
        Syntax :     public Boolean getDiscard()  
  9. setPortList() : Käytetään määrittämään portit, joita tämä eväste voi käyttää.
        Syntax :     public void setPortList(String portList)   
    Parameters :
    portList : String of comma separated digits specifying the ports.
  10. getPortList() : Palauttaa luettelon porteista, joita tämä eväste voi käyttää.
        Syntax :     public String getPortList()  
  11. setDomain() : Määritä verkkotunnus, jossa tämän evästeen tulee olla näkyvissä. Esimerkiksi servletistä osoitteessa bali.vacations.com lähetetyt evästeet eivät normaalisti palauteta selaimelta sivuille osoitteessa queensland.vacations.com. Jos sivusto halusi tämän tapahtuvan, servletit voisivat määrittää cookie.setDomain(.vacations.com). Jotta palvelimet eivät aseta evästeitä, jotka koskevat verkkotunnuksensa ulkopuolella olevia isäntiä, määritetyn verkkotunnuksen on täytettävä seuraavat vaatimukset: sen on alettava pisteellä (esim. .coreservlets.com).
        Syntax :     public void setDomain(String domain)   
    Parameters :
    domain : String representing the domain in which this cookie is visible
  12. getDomain() : Palauttaa verkkotunnuksen, jossa tämä eväste on näkyvissä.
        Syntax :     public String getDomain()  
  13. setMaxAge() : käytetään asettamaan evästeen enimmäisikä sekunneissa. Se määrittää enimmäisajan evästeen luomisen jälkeen, jonka se on elossa. Negatiiviset arvot määrittelevät, että eväste vanhenee heti, kun selain suljetaan.
        Syntax :     public void setMaxAge(long age)   
    Parameters :
    age : Max survive time in seconds
  14. getMaxAge() : Palauttaa evästeen enimmäisiän.
        Syntax :     public long getMaxAge()  
  15. setPath() : Käytetään määrittämään polku asiakkaalle, jolle sen tulee palauttaa eväste. Tämä eväste näkyy kaikille määritetyn polun sivuille ja alihakemistoille. Jos palvelin esimerkiksi lähetti evästeen osoitteesta http://ecommerce.site.com/toys/specials.html, selain lähettää evästeen takaisin muodostaessaan yhteyden osoitteeseen http://ecommerce.site.com/to/beginners.html, mutta ei osoitteeseen http://ecommerce.site.com/c/classic.html.
        Syntax :     public void setPath(String uri)   
    Parameters :
    uri - a String specifying a path
  16. getPath() : Palauttaa tälle evästeelle asetetun polun.
        Syntax :     public String getPath()  
  17. Java-toteutus:
  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. Lähtö
  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() : Osoitetaan, käytetäänkö suojattua protokollaa tämän evästeen lähettämisessä. Oletusarvo on 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() : Palauttaa tosi, jos tämä eväste on lähetettävä suojatulla protokollalla, muuten epätosi.
        Syntax :     public boolean getSecure()  
  23. getName() : Palauttaa evästeen nimen.
           Syntax :     public String getName()  
  24. setValue() : Määrittää evästeelle uuden arvon alustamisen jälkeen.
        Syntax :     public void setValue(String newValue)   
    Parameters :
    newValue - a String specifying the new value
  25. getValue: Palauttaa evästeen arvon.
        Syntax :     public String getValue()  
  26. getVersion() : Palauttaa 0, jos eväste on alkuperäisen Netscape-määrityksen mukainen; 1, jos eväste on RFC 2965/2109 -standardin mukainen
        Syntax :     public int getVersion()  
  27. setVersion() : Käytetään asettamaan evästeprotokollan versio, jota tämä eväste käyttää.
        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() : Palauttaa tosi, jos evästettä voi käyttää vain http eli sitä eivät voi käyttää komentosarjakielet, kuten JS vb jne.
        Syntax :     public boolean isHttpOnly()  
  29. setHttpOnly() : Käytetään määrittämään, onko tämä eväste vain http vai ei.
        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() : Apuohjelma tarkistaa, onko isäntänimi toimialueella vai ei.
        Syntax :     public static boolean domainMatches(String domain   
    String host)
    Parameters :
    domain : domain to check hostname with
    host : host to check
  31. toString() : Muodostaa tästä evästeestä merkkijonoesityksen.
           Syntax :    public String toString()  
  32. yhtä kuin () : palauttaa tosi, jos kaksi http-evästettä ovat keskenään yhtä suuret, false.
           Syntax :    public boolean equals(Object obj)  
  33. hashCode() : Palauta tämän http-evästeen hash-koodi. Tuloksena on tämän evästeen kolmen merkittävän komponentin hash-koodin arvon summa: nimi domain ja polku. Ohittaa hashCoden luokassa Object.
        Syntax :     public int hashCode()  
  34. klooni(): Luo ja palauta kopio tästä objektista. Ohittaa objektiluokan kloonausmenetelmän.
        Syntax :     public Object clone()  

Java-toteutus:

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  ());      }   }   

Lähtö:

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

Toinen esimerkki siitä, kuinka web-palvelimet todella käyttävät evästeitä, joissa tulostetaan www.facebook.comin tallentamien evästeiden tiedot.

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  ());      }      }   }   

Lähtö:

 ------------------ 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

Viite:

Virallinen Java-dokumentaatio

Luo tietokilpailu