Java.net.HttpJava'da Çerez
Önkoşul - Çerezler
Birçok web sitesi, bağlantılar arasında kalıcı istemci tarafı durumunu depolamak için çerez olarak bilinen küçük metin dizilerini kullanır. Çerezler sunucudan istemciye ve istek ve yanıtların HTTP başlıklarında tekrar aktarılır. Çerezler bir sunucu tarafından oturum kimliklerini, alışveriş sepeti içeriğini, oturum açma kimlik bilgilerini, kullanıcı tercihlerini ve daha fazlasını belirtmek için kullanılabilir. Bir HttpCookie nesnesi, sunucu ile kullanıcı aracısı arasında durum bilgilerini taşıyan bir http çerezini temsil eder. Çerez, durum bilgisi olan oturumlar oluşturmak için yaygın olarak kullanılmaktadır. 3 http çerez spesifikasyonu vardır:
HttpCookie sınıfı bu 3 sözdiziminin tümünü kabul edebilir.
Yapıcı:
Belirtilen ad ve değere sahip bir çerez oluşturur. Ad yalnızca ASCII alfasayısal karakterler içermeli ve RFC 2965'e uygun olmalıdır. Ad doğru değilse bir IllegalArgument istisnası veya ad null ise NullPointerException oluşturur. Değer, çerezin saklamak istediği herhangi bir şey olabilir.
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 nullYöntemler:
- ayrıştırma(): başlık dizesinden ayrıştırılan çerezlerin bir listesini döndürür. başlık set-cookie veya set-cookie2 token ile başlamalı veya herhangi bir token içermemelidir.
Syntax : public static List parse(String header)
Parameters :
header : String to be parsed as cookies- hasExpired(): Çerezin süresinin dolup dolmadığını belirten boole değerini döndürür.
Syntax : public boolean hasExpired()- setComment() : Çerezin amacını açıklayan kısa bir açıklama ayarlamak için kullanılır. Çerezin kullanıcıya ne zaman sunulacağı kullanılır.
Syntax : public void setComment(String purpose)
Parameters :
purpose : purpose of cookie- getComment() : Çerezin açıklamasını döndürür veya çerezin hiçbir yorumu yoksa null değerini döndürür.
Syntax : public void getComment()- setCommentURL() : Çerezin amacını açıklayan kısa bir yorum URL'si ayarlamak için kullanılır. Tarayıcı çerezi kullanıcıya sunduğunda kullanılır.
Syntax : public void setCommentURL(String purpose)
Parameters :
purpose : purpose of cookie- getCommentURL(): Çerezin URL yorumunu döndürür veya çerezin URL yorumu yoksa null değerini döndürür.
Syntax : public String getComment()- setDiscard(): Kullanıcı aracısının bu çerezi atması gerekip gerekmediğini ayarlamak için kullanılır.
Syntax : public void setDiscard(Boolean discard)
Parameters :
discard : true if UA should discard otherwise false- getDiscard(): setDiscard() yöntemiyle ayarlanan atılan değişkenin durumunu döndürür. Daha spesifik olarak, eğer UA bu çerezi atacaksa true değerini döndürür, aksi takdirde false değerini döndürür.
Syntax : public Boolean getDiscard()- setPortList(): Bu çerezin kullanabileceği bağlantı noktalarını belirtmek için kullanılır.
Syntax : public void setPortList(String portList)
Parameters :
portList : String of comma separated digits specifying the ports.- getPortList(): Bu çerezin kullanabileceği bağlantı noktalarının listesini döndürür.
Syntax : public String getPortList()- setDomain(): Bu çerezin görünür olacağı etki alanını belirtin. Örneğin, bali.vacations.com adresindeki bir sunucu uygulamasından gönderilen çerezler normalde tarayıcı tarafından queensland.vacations.com adresindeki sayfalara döndürülmez. Site bunun olmasını istiyorsa sunucu uygulamaları cookie.setDomain(.vacations.com) adresini belirtebilir. Sunucuların, kendi etki alanları dışındaki ana bilgisayarlar için geçerli olan çerezleri ayarlamasını önlemek için, belirtilen etki alanının aşağıdaki gereksinimleri karşılaması gerekir: bir noktayla başlamalıdır (ör. .coreservlets.com).
Syntax : public void setDomain(String domain)
Parameters :
domain : String representing the domain in which this cookie is visible- getDomain(): Bu çerezin görünür olduğu etki alanını döndürür.
Syntax : public String getDomain()- setMaxAge(): Çerezin maksimum yaşını saniye cinsinden ayarlamak için kullanılır. Canlı olduğu çerezin oluşturulmasından sonraki maksimum süreyi belirtir. Negatif değerler, tarayıcıdan çıkar çıkmaz çerezin süresinin dolacağını belirtir.
Syntax : public void setMaxAge(long age)
Parameters :
age : Max survive time in seconds- getMaxAge(): Çerezin maksimum yaşını döndürür.
Syntax : public long getMaxAge()- setPath(): Çerezleri döndürmesi gereken istemcinin yolunu belirtmek için kullanılır. Bu çerez, belirtilen yolun tüm sayfaları ve alt dizinleri tarafından görülebilir. Örneğin, sunucu çerezi http://ecommerce.site.com/toys/specials.html adresinden göndermişse, tarayıcı http://ecommerce.site.com/to/beginners.html adresine bağlanırken çerezi geri gönderir ancak http://ecommerce.site.com/c/classic.html'ye bağlanmaz.
Syntax : public void setPath(String uri)
Parameters :
uri - a String specifying a path- getPath(): Bu tanımlama bilgisi için ayarlanan yolu döndürür.
Syntax : public String getPath()- Java'nın Uygulanması:
- 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 ()); } }- Çıkış
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(): Bu çerez gönderilirken güvenli protokolün kullanılacağı belirtilir. Varsayılan değer false'tur.
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(): Bu çerezin güvenli bir protokolle gönderilmesi gerekiyorsa true değerini döndürür, aksi takdirde false değerini döndürür.
Syntax : public boolean getSecure()- getName(): Çerezin adını döndürür.
Syntax : public String getName()- setValue(): Başlatma sonrasında çerezlere yeni değer atar.
Syntax : public void setValue(String newValue)
Parameters :
newValue - a String specifying the new value- getValue : Çerezin değerini döndürür.
Syntax : public String getValue()- getVersion(): Çerez orijinal Netscape spesifikasyonuna uygunsa 0 değerini döndürür; Çerez RFC 2965/2109 ile uyumluysa 1
Syntax : public int getVersion()- setVersion(): Bu çerezin kullandığı çerez protokolünün sürümünü ayarlamak için kullanılır.
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(): Çerez yalnızca http tarafından kullanılabiliyorsa, yani JS vb. gibi kodlama dilleri tarafından kullanılamıyorsa doğru değerini döndürür.
Syntax : public boolean isHttpOnly()- setHttpOnly(): Bu çerezin yalnızca http olup olmadığını ayarlamak için kullanılır.
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() : Ana makine adının etki alanında olup olmadığını kontrol eden yardımcı program işlevi.
Syntax : public static boolean domainMatches(String domain
String host)
Parameters :
domain : domain to check hostname with
host : host to check- toString(): Bu tanımlama bilgisinin dize temsilini oluşturur.
Syntax : public String toString()- eşittir(): İki http çerezi birbirine eşitse true değerini döndürür, aksi takdirde false değerini döndürür.
Syntax : public boolean equals(Object obj)- hashCode(): Bu http çerezinin karma kodunu döndürün. Sonuç, bu çerezin üç önemli bileşeninin karma kod değerinin toplamıdır: alan adı ve yol. Object sınıfındaki hashCode'u geçersiz kılar.
Syntax : public int hashCode()- klon(): Bu nesnenin bir kopyasını oluşturun ve döndürün. Nesne sınıfının klon yöntemini geçersiz kılar.
Syntax : public Object clone()Java'nın Uygulanması:
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 ()); } }Çıkış :
Secure : true
Name : First
Value : 2
Version : 1
is HTTP only : true
toString : First='2'
Hashcode : 97440432www.facebook.com tarafından saklanan çerezlerin ayrıntılarını yazdırdığımız Web sunucuları tarafından çerezlerin gerçekte nasıl kullanıldığını gösteren başka bir örnek
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 ()); } } }Çıkış :
------------------ 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: 0Referans:
Resmi Java BelgeleriTest Oluştur