Java.net.HttpCookie in Java
Prerequisito - Biscotti
Molti siti Web utilizzano piccole stringhe di testo note come cookie per archiviare lo stato persistente lato client tra le connessioni. I cookie vengono passati dal server al client e viceversa nelle intestazioni HTTP di richieste e risposte. I cookie possono essere utilizzati da un server per indicare gli ID di sessione, i contenuti del carrello, le credenziali di accesso, le preferenze dell'utente e altro ancora. Un oggetto HttpCookie rappresenta un cookie http che trasporta informazioni sullo stato tra il server e l'agente utente. I cookie sono ampiamente utilizzati per creare sessioni con stato. Esistono 3 specifiche dei cookie http:
La classe HttpCookie può accettare tutte queste 3 forme di sintassi.
Costruttore:
Crea un cookie con il nome e il valore specificati. Il nome deve contenere solo caratteri alfanumerici ASCII ed essere conforme a RFC 2965. Genera un'eccezione IllegalArgument se il nome non è corretto o NullPointerException se nome è null. Il valore può essere qualsiasi cosa il cookie voglia memorizzare.
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 nullMetodi:
- analizzare(): restituisce un elenco di cookie analizzati dalla stringa di intestazione. l'intestazione deve iniziare con set-cookie o token set-cookie2 o non deve contenere alcun token.
Syntax : public static List parse(String header)
Parameters :
header : String to be parsed as cookies- èscaduto() : restituisce un valore booleano che indica se il cookie è scaduto o meno.
Syntax : public boolean hasExpired()- setComment() : Utilizzato per impostare una breve descrizione che descrive lo scopo del cookie. Viene utilizzato quando presentare il cookie all'utente.
Syntax : public void setComment(String purpose)
Parameters :
purpose : purpose of cookie- getCommento() : Restituisce la descrizione del cookie o null se il cookie non ha commenti.
Syntax : public void getComment()- setCommentURL() : Utilizzato per impostare un breve URL di commento che descrive lo scopo del cookie. Viene utilizzato quando il browser presenta il cookie all'utente.
Syntax : public void setCommentURL(String purpose)
Parameters :
purpose : purpose of cookie- getCommentURL() : Restituisce il commento URL del cookie o null se il cookie non ha commenti URL.
Syntax : public String getComment()- setDiscard() : Utilizzato per impostare se l'agente utente deve scartare questo cookie o meno.
Syntax : public void setDiscard(Boolean discard)
Parameters :
discard : true if UA should discard otherwise false- getDiscard() : Restituisce lo stato della variabile di scarto impostata dal metodo setDiscard(). Più specificatamente restituisce true se UA deve scartare questo cookie, altrimenti false.
Syntax : public Boolean getDiscard()- setPortList() : Utilizzato per specificare le porte che questo cookie può utilizzare.
Syntax : public void setPortList(String portList)
Parameters :
portList : String of comma separated digits specifying the ports.- getListaPorte() : Restituisce l'elenco delle porte che questo cookie può utilizzare.
Syntax : public String getPortList()- setDomain() : Specificare il dominio in cui questo cookie dovrebbe essere visibile. Ad esempio, i cookie inviati da un servlet su bali.vacations.com normalmente non verrebbero restituiti dal browser alle pagine su queensland.vacations.com. Se il sito volesse che ciò accada, i servlet potrebbero specificare cookie.setDomain(.vacations.com). Per impedire ai server di impostare cookie che si applicano a host esterni al proprio dominio, il dominio specificato deve soddisfare i seguenti requisiti: deve iniziare con un punto (ad esempio .coreservlets.com).
Syntax : public void setDomain(String domain)
Parameters :
domain : String representing the domain in which this cookie is visible- getDomain() : Restituisce il dominio in cui questo cookie è visibile.
Syntax : public String getDomain()- setMaxAge() : utilizzato per impostare la durata massima dei cookie in secondi. Specifica il tempo massimo dopo la creazione del cookie per il quale è vivo. I valori negativi specificano che il cookie scadrà non appena il browser verrà chiuso.
Syntax : public void setMaxAge(long age)
Parameters :
age : Max survive time in seconds- getMaxAge() : Restituisce la durata massima del cookie.
Syntax : public long getMaxAge()- setPath() : Utilizzato per specificare il percorso del client in cui deve restituire il cookie. Questo cookie è visibile a tutte le pagine e sottodirectory del percorso specificato. Ad esempio, se il server inviasse il cookie da http://ecommerce.site.com/toys/specials.html, il browser invierebbe nuovamente il cookie quando si connette a http://ecommerce.site.com/to/beginners.html ma non a http://ecommerce.site.com/c/classic.html.
Syntax : public void setPath(String uri)
Parameters :
uri - a String specifying a path- getPath() : Restituisce il percorso impostato per questo cookie.
Syntax : public String getPath()- Implementazione Java:
- 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 ()); } }- Produzione
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- setSecure() : Indicato se il protocollo sicuro da utilizzare durante l'invio di questo cookie. Il valore predefinito è falso.
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.- getSecure() : Restituisce vero se questo cookie deve essere inviato tramite un protocollo sicuro altrimenti falso.
Syntax : public boolean getSecure()- getNome() : Restituisce il nome del cookie.
Syntax : public String getName()- setValore() : Assegna un nuovo valore al cookie dopo l'inizializzazione.
Syntax : public void setValue(String newValue)
Parameters :
newValue - a String specifying the new value- getValore: Restituisce il valore del cookie.
Syntax : public String getValue()- getVersion() : Restituisce 0 se il cookie è conforme alla specifica originale di Netscape; 1 se il cookie è conforme alla RFC 2965/2109
Syntax : public int getVersion()- setVersione() : Utilizzato per impostare la versione del protocollo cookie utilizzato da questo 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- isHttpOnly() : Restituisce vero se il cookie può essere utilizzato solo da http, ovvero non può essere utilizzato da linguaggi di scripting come JS vb ecc.
Syntax : public boolean isHttpOnly()- setHttpOnly() : Utilizzato per impostare se questo cookie è solo http o meno.
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.- domainMatches() : Funzione di utilità per verificare se il nome host è nel dominio o meno.
Syntax : public static boolean domainMatches(String domain
String host)
Parameters :
domain : domain to check hostname with
host : host to check- aStringa() : Costruisce una rappresentazione di stringa di questo cookie.
Syntax : public String toString()- è uguale(): restituisce vero se due cookie http sono uguali tra loro falso altrimenti.
Syntax : public boolean equals(Object obj)- codicehash() : Restituisce il codice hash di questo cookie http. Il risultato è la somma del valore del codice hash di tre componenti significativi di questo cookie: nome, dominio e percorso. Sostituisce hashCode nella classe Object.
Syntax : public int hashCode()- clone() : Crea e restituisce una copia di questo oggetto. Sostituisce il metodo clone della classe dell'oggetto.
Syntax : public Object clone()Implementazione 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 ()); } }Produzione :
Secure : true
Name : First
Value : 2
Version : 1
is HTTP only : true
toString : First='2'
Hashcode : 97440432Un altro esempio per mostrare come i cookie vengono effettivamente utilizzati dai server Web in cui stampiamo i dettagli dei cookie memorizzati da www.facebook.com
Javaimport 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 ()); } } }Produzione :
------------------ 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: 0Riferimento:
Documentazione Java ufficialeCrea quiz