logo

Java.net.HttpCookie ב-Java

תנאי מוקדם - עוגיות

אתרי אינטרנט רבים משתמשים במחרוזות טקסט קטנות הידועות כקובצי Cookie כדי לאחסן מצב מתמשך בצד הלקוח בין חיבורים. קובצי Cookie מועברים משרת ללקוח וחוזר חלילה בכותרות HTTP של בקשות ותגובות. שרת יכול להשתמש בקובצי Cookie כדי לציין מזהי הפעלה תוכן עגלת קניות אישורי כניסה העדפות משתמש ועוד. אובייקט HttpCookie מייצג קובץ cookie http הנושא מידע מצב בין השרת לסוכן המשתמש. Cookie מאומצת באופן נרחב כדי ליצור הפעלות ממלכתיות. ישנם 3 מפרטי קובצי cookie http:



מחלקה HttpCookie יכולה לקבל את כל 3 צורות התחביר הללו.

קונסטרוקטור:

יוצר קובץ Cookie עם השם והערך שצוינו. השם חייב להכיל רק תווים אלפאנומריים ASCII ולהתאים ל-RFC 2965. הוא זורק חריג IllegalArgument אם השם אינו נכון או NullPointerException אם השם הוא null. הערך יכול להיות כל מה שעוגייה רוצה לאחסן.

    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. parse() : מחזירה רשימה של קובצי 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 למשתמש.
        Syntax :    public void setComment(String purpose)  
    Parameters :
    purpose : purpose of cookie
  4. getComment() : מחזירה את תיאור ה-cookie או null אם ל-cookie אין הערות.
        Syntax :    public void getComment()
  5. setCommentURL() : משמש להגדרת כתובת אתר קצרה של תגובה המתארת ​​את מטרת ה-cookie. הוא משמש כאשר הדפדפן מציג את קובץ ה-cookie למשתמש.
        Syntax :    public void setCommentURL(String purpose)  
    Parameters :
    purpose : purpose of cookie
  6. getCommentURL() : מחזירה את הערת ה-URL של קובץ ה-cookie או null אם ל-cookie אין הערות כתובת URL.
        Syntax :    public String getComment()
  7. setDiscard() : משמש כדי להגדיר אם סוכן המשתמש צריך לזרוק את העוגייה הזו או לא.
        Syntax :    public void setDiscard(Boolean discard)  
    Parameters :
    discard : true if UA should discard otherwise false
  8. getDiscard() : מחזירה את מצב המשתנה Discard שנקבע על ידי שיטת setDiscard() . ליתר דיוק מחזירה true אם UA לזרוק את ה-cookie הזה אחרת שקר.
        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() : ציין את התחום שבו קובץ ה-cookie הזה אמור להיות גלוי. לדוגמה, עוגיות שנשלחו משרת בכתובת bali.vacations.com לא יוחזרו בדרך כלל על ידי הדפדפן לדפים בכתובת 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 יפוג ברגע שהדפדפן יוצא.
        Syntax :    public void setMaxAge(long age)  
    Parameters :
    age : Max survive time in seconds
  14. getMaxAge() : מחזירה את הגיל המרבי של קובצי Cookie.
        Syntax :    public long getMaxAge()
  15. setPath(): משמש כדי לציין את הנתיב ללקוח שבו עליו להחזיר את ה-cookie. קובץ Cookie זה גלוי לכל הדפים וספריות המשנה של הנתיב שצוין. לדוגמה, אם השרת שלח את קובץ ה-cookie מ-http://ecommerce.site.com/toys/specials.html, הדפדפן ישלח את ה-cookie בחזרה בעת חיבור אל 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() : מחזירה את הנתיב שהוגדר עבור קובץ 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 זה. ערך ברירת המחדל הוא שקר.
        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 אם קובץ ה-cookie הזה חייב להישלח על ידי פרוטוקול מאובטח אחרת שקר.
        Syntax :    public boolean getSecure()
  23. getName() : מחזירה את שם ה-cookie.
         Syntax :    public String getName()
  24. setValue() : מקצה ערך חדש לעוגייה לאחר האתחול.
        Syntax :    public void setValue(String newValue)  
    Parameters :
    newValue - a String specifying the new value
  25. getValue: מחזירה את הערך של קובץ ה-cookie.
        Syntax :    public String getValue()
  26. getVersion() : מחזירה 0 אם ה-cookie תואם את המפרט המקורי של Netscape; 1 אם קובץ ה-cookie תואם ל-RFC 2965/2109
        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() : מחזירה true אם ניתן להשתמש ב-cookie רק על ידי http כלומר לא ניתן להשתמש בו על ידי שפות סקריפטים כמו JS vb וכו'.
        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. שווה() : מחזירה true אם שתי עוגיות http שווים זה לזה false אחרת.
         Syntax :   public boolean equals(Object obj)
  33. hashCode(): החזר קוד hash של קובץ ה-http קובץ Cookie זה. התוצאה היא סכום ערך קוד ה-hash של שלושה מרכיבים משמעותיים של קובץ cookie זה: שם דומיין ונתיב. עוקף hashCode ב-class Object.
        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

דוגמה נוספת להראות כיצד עוגיות משמשות בפועל על ידי שרתי אינטרנט שבהם אנו מדפיסים את פרטי העוגיות המאוחסנות על ידי 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

הַפנָיָה:

תיעוד ג'אווה רשמי

צור חידון