![]() |
||||||
|
||||||
|
À̹ø È£¿¡¼´Â, » CookieHandler¸¦ ÀÌ¿ëÇÑ ÄíŰ °ü¸® » Å×Å©ÆÁ ÄûÁî Á¤´ä À» ´Ù·ç°Ô µË´Ï´Ù. |
||
| CookieHandler¸¦ ÀÌ¿ëÇÑ ÄíŰ °ü¸® | ||
|
ÀÚ¹Ù Ç÷§ÆûÀÇ °æ¿ì, URLÀ» ÅëÇÑ ¿ÀºêÁ§Æ® ¾×¼¼½º´Â ÀÏ·ÃÀÇ ÇÁ·ÎÅäÄÝ Çڵ鷯¿¡ ÀÇÇØ °ü¸®µÈ´Ù. URLÀÇ Ã¹ ºÎºÐÀº »ç¿ëµÇ´Â ÇÁ·ÎÅäÄÝÀ» ¾Ë·ÁÁִµ¥, ¿¹¸¦ µé¾î URLÀÌ
J2SE 5.0Àº http ÇÁ·ÎÅäÄÝ Çڵ鷯 ±¸ÇöÀÇ ÀϺηΠJ2SE 5.0¿¡¼ ±âº»°ªÀ¸·Î ¼³Ä¡µÇ´Â Çڵ鷯´Â ¾øÀ¸³ª, Çڵ鷯¸¦ µî·ÏÇÏ¿© ¾ÖÇø®ÄÉÀ̼ÇÀÌ Äí۸¦ ±â¾ïÇß´Ù°¡ http Á¢¼Ó ½Ã¿¡ À̸¦ ¹Ý¼ÛÇϵµ·Ï ÇÒ ¼ö´Â ÀÖ´Ù.
º¸¾È ¸Å´ÏÀú°¡ ¼³Ä¡µÈ ¾ÖÇø®ÄÉÀ̼ÇÀÇ °æ¿ì, Çڵ鷯¸¦ ¾ò°í À̸¦ ¼³Á¤ÇÏ·Á¸é Ưº° Çã°¡¸¦ ¹Þ¾Æ¾ß ÇÑ´Ù. ÇöÀçÀÇ Çڵ鷯¸¦ Á¦°ÅÇÏ·Á¸é Çڵ鷯·Î nullÀ» ÀÔ·ÂÇÑ´Ù. ¶ÇÇÑ ¾Õ¼ ¾ê±âÇßµíÀÌ ±âº»°ªÀ¸·Î ¼³Á¤µÇ¾î ÀÖ´Â Çڵ鷯´Â ¾ø´Ù. µÎ ¹øÂ° ½ÖÀÇ ¸Þ¼Òµå´Â °¢ÀÚ°¡ °ü¸®ÇÏ´Â ÄíŰ ij½Ã·ÎºÎÅÍ Äí۸¦ ¾ò°í À̸¦ ¼³Á¤ÇÒ ¼ö ÀÖ°Ô ÇÑ´Ù.
¿©±â¼ º¸µíÀÌ Çڵ鷯¸¦ ÀÛ¼ºÇÏ´Â ÀÏÀº ½ÇÁ¦·Î´Â °£´ÜÇÏ´Ù. ±×·¯³ª ij½Ã¸¦ Á¤ÀÇÇÏ´Â µ¥´Â ¾à°£ÀÇ Ãß°¡ ÀÛ¾÷ÀÌ ´õ ÇÊ¿äÇÏ´Ù. ÀÏ·Ê·Î, Ä¿½ºÅÒ
import java.io.*;
import java.net.*;
import java.util.*;
public class Fetch {
public static void main(String args[]) throws Exception {
if (args.length == 0) {
System.err.println("URL missing");
System.exit(-1);
}
String urlString = args[0];
CookieHandler.setDefault(new ListCookieHandler());
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
Object obj = connection.getContent();
url = new URL(urlString);
connection = url.openConnection();
obj = connection.getContent();
}
}
¸ÕÀú ÀÌ ÇÁ·Î±×·¥Àº °£·«ÇÏ°Ô Á¤ÀǵÉ
ÀÌÁ¦ À̰ÍÀ» °ü¸®ÇÏ´Â ¹æ¹ý¿¡ ´ëÇØ ¾Ë¾Æº¸±â·Î ÇÏÀÚ. óÀ½¿¡´Â String urlString = ...; URL url = new URL(urlString); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); // .. read content from stream
Á¢¼ÓÀ¸·ÎºÎÅÍ ÀÌ¿ë °¡´ÉÇÑ Á¤º¸¿¡´Â ÀÏ·ÃÀÇ Çì´õµéÀÌ Æ÷Ç﵃ ¼ö Àִµ¥, ÀÌ´Â »ç¿ëÁßÀÎ ÇÁ·ÎÅäÄÝ¿¡ ÀÇÇØ °áÁ¤µÈ´Ù. Çì´õ¸¦ ãÀ¸·Á¸é
ÀÏ·Ê·Î, ´ÙÀ½ ÇÁ·Î±×·¥Àº ÁÖ¾îÁø URLÀÇ ¸ðµç Çì´õ¸¦ ¿°ÅÇÑ´Ù
import java.net.*;
import java.util.*;
public class ListHeaders {
public static void main(String args[]) throws Exception {
if (args.length == 0) {
System.err.println("URL missing");
}
String urlString = args[0];
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
Map<String,List<String>> headerFields =
connection.getHeaderFields();
Set<String> set = headerFields.keySet();
Iterator<String> itor = set.iterator();
while (itor.hasNext()) {
String key = itor.next();
System.out.println("Key: " + key + " / " +
headerFields.get(key));
}
}
}
Key: <key> / [<value>] µû¶ó¼ ´ÙÀ½À» ÀÔ·ÂÇϸé, >> java ListHeaders http://java.sun.com ´ÙÀ½°ú À¯»çÇÑ ³»¿ëÀÌ Ç¥½ÃµÇ¾î¾ß ÇÑ´Ù. Key: Set-Cookie / [SUN_ID=192.168.0.1:269421125489956; EXPIRES=Wednesday, 31- Dec-2025 23:59:59 GMT; DOMAIN=.sun.com; PATH=/] Key: Set-cookie / [JSESSIONID=688047FA45065E07D8792CF650B8F0EA;Path=/] Key: null / [HTTP/1.1 200 OK] Key: Transfer-encoding / [chunked] Key: Date / [Wed, 31 Aug 2005 12:05:56 GMT] Key: Server / [Sun-ONE-Web-Server/6.1] Key: Content-type / [text/html;charset=ISO-8859-1] (À§¿¡ Ç¥½ÃµÈ °á°ú¿¡¼ ±ä ÇàÀº ¼öµ¿À¸·Î ÁٹٲÞÇÑ °ÍÀÓ) ÀÌ´Â ÇØ´ç URL¿¡ ´ëÇÑ Çì´õµé¸¸À» Ç¥½ÃÇϸç, ±×°÷¿¡ À§Ä¡ÇÑ HTML ÆäÀÌÁö´Â Ç¥½ÃÇÏÁö ¾Ê´Â´Ù. Ç¥½ÃµÇ´Â Á¤º¸¿¡´Â »çÀÌÆ®¿¡¼ »ç¿ëÇÏ´Â À¥ ¼¹ö¿Í ·ÎÄà ½Ã½ºÅÛÀÇ ³¯Â¥ ¹× ½Ã°£ÀÌ Æ÷ÇԵǴ »ç½Ç¿¡ À¯ÀÇÇÒ °Í. ¾Æ¿ï·¯ 2°³ÀÇ ¡®Set-Cookie¡¯ Çà¿¡µµ À¯ÀÇÇØ¾ß ÇÑ´Ù. À̵éÀº ÄíŰ¿Í °ü·ÃµÈ Çì´õµéÀ̸ç, ÄíŰ´Â Çì´õ·ÎºÎÅÍ ÀúÀåµÈ µÚ ´ÙÀ½ÀÇ ¿äû°ú ÇÔ²² Àü¼ÛµÉ ¼ö ÀÖ´Ù.
ÀÌÁ¦
¿ì¼±
List<String> setCookieList =
responseHeaders.get("Set-Cookie");
ÄíŰÀÇ ¸®½ºÆ®¸¦ È®º¸ÇÑ ÈÄ °¢ Äí۸¦ ¹Ýº¹(loop)Çϰí ÀúÀåÇÑ´Ù. Äí۰¡ ÀÌ¹Ì Á¸ÀçÇÒ °æ¿ì¿¡´Â ±âÁ¸ÀÇ °ÍÀ» ±³Ã¼Çϵµ·Ï ÇÑ´Ù.
if (setCookieList != null) {
for (String item : setCookieList) {
Cookie cookie = new Cookie(uri, item);
// Remove cookie if it already exists in cache
// New one will replace it
for (Cookie existingCookie : cache) {
...
}
System.out.println("Adding to cache: " + cookie);
cache.add(cookie);
}
}
¿©±â¼ ¡®Ä³½Ã¡¯´Â µ¥ÀÌÅͺ£À̽º¿¡¼ Collections Framework¿¡¼
º»ÁúÀûÀ¸·Î, ±×°ÍÀÌ
// Retrieve all the cookies for matching URI
// Put in comma-separated list
StringBuilder cookies = new StringBuilder();
for (Cookie cookie : cache) {
// Remove cookies that have expired
if (cookie.hasExpired()) {
cache.remove(cookie);
} else if (cookie.matches(uri)) {
if (cookies.length() > 0) {
cookies.append(", ");
}
cookies.append(cookie.toString());
}
}
ÀÌ °æ¿ì¿¡µµ
// Map to return
Map<String, List<String>> cookieMap =
new HashMap<String, List<String>>(requestHeaders);
// Convert StringBuilder to List, store in map
if (cookies.length() > 0) {
List<String> list =
Collections.singletonList(cookies.toString());
cookieMap.put("Cookie", list);
}
return Collections.unmodifiableMap(cookieMap);
´ÙÀ½Àº ·±Å¸ÀÓÀÇ Á¤º¸ Ç¥½Ã¸¦ À§ÇØ
import java.io.*;
import java.net.*;
import java.util.*;
public class ListCookieHandler extends CookieHandler {
// "Long" term storage for cookies, not serialized so only
// for current JVM instance
private List<Cookie> cache = new LinkedList<Cookie>();
/**
* Saves all applicable cookies present in the response
* headers into cache.
* @param uri URI source of cookies
* @param responseHeaders Immutable map from field names to
* lists of field
* values representing the response header fields returned
*/
public void put(
URI uri,
Map<String, List<String>> responseHeaders)
throws IOException {
System.out.println("Cache: " + cache);
List<String> setCookieList =
responseHeaders.get("Set-Cookie");
if (setCookieList != null) {
for (String item : setCookieList) {
Cookie cookie = new Cookie(uri, item);
// Remove cookie if it already exists
// New one will replace
for (Cookie existingCookie : cache) {
if((cookie.getURI().equals(
existingCookie.getURI())) &&
(cookie.getName().equals(
existingCookie.getName()))) {
cache.remove(existingCookie);
break;
}
}
System.out.println("Adding to cache: " + cookie);
cache.add(cookie);
}
}
}
/**
* Gets all the applicable cookies from a cookie cache for
* the specified uri in the request header.
*
* @param uri URI to send cookies to in a request
* @param requestHeaders Map from request header field names
* to lists of field values representing the current request
* headers
* @return Immutable map, with field name "Cookie" to a list
* of cookies
*/
public Map<String, List<String>> get(
URI uri,
Map<String, List<String>> requestHeaders)
throws IOException {
// Retrieve all the cookies for matching URI
// Put in comma-separated list
StringBuilder cookies = new StringBuilder();
for (Cookie cookie : cache) {
// Remove cookies that have expired
if (cookie.hasExpired()) {
cache.remove(cookie);
} else if (cookie.matches(uri)) {
if (cookies.length() > 0) {
cookies.append(", ");
}
cookies.append(cookie.toString());
}
}
// Map to return
Map<String, List<String>> cookieMap =
new HashMap<String, List<String>>(requestHeaders);
// Convert StringBuilder to List, store in map
if (cookies.length() > 0) {
List<String> list =
Collections.singletonList(cookies.toString());
cookieMap.put("Cookie", list);
}
System.out.println("Cookies: " + cookieMap);
return Collections.unmodifiableMap(cookieMap);
}
}
ÆÛÁñÀÇ ¸¶Áö¸· Á¶°¢Àº
public Cookie(URI uri, String header) {
String attributes[] = header.split(";");
String nameValue = attributes[0].trim();
this.uri = uri;
this.name = nameValue.substring(0, nameValue.indexOf('='));
this.value = nameValue.substring(nameValue.indexOf('=')+1);
this.path = "/";
this.domain = uri.getHost();
for (int i=1; i < attributes.length; i++) {
nameValue = attributes[i].trim();
int equals = nameValue.indexOf('=');
if (equals == -1) {
continue;
}
String name = nameValue.substring(0, equals);
String value = nameValue.substring(equals+1);
if (name.equalsIgnoreCase("domain")) {
String uriDomain = uri.getHost();
if (uriDomain.equals(value)) {
this.domain = value;
} else {
if (!value.startsWith(".")) {
value = "." + value;
}
uriDomain =
uriDomain.substring(uriDomain.indexOf('.'));
if (!uriDomain.equals(value)) {
throw new IllegalArgumentException(
"Trying to set foreign cookie");
}
this.domain = value;
}
} else if (name.equalsIgnoreCase("path")) {
this.path = value;
} else if (name.equalsIgnoreCase("expires")) {
try {
this.expires = expiresFormat1.parse(value);
} catch (ParseException e) {
try {
this.expires = expiresFormat2.parse(value);
} catch (ParseException e2) {
throw new IllegalArgumentException(
"Bad date format in header: " + value);
}
}
}
}
}
Ŭ·¡½º ³»ÀÇ ´Ù¸¥ ¸Þ¼ÒµåµéÀº ´ÜÁö ÀúÀåµÈ µ¥ÀÌÅ͸¦ ¹ÝȯÇϰųª ¸¸·á ¿©ºÎ¸¦ È®ÀÎÇÑ´Ù.
public boolean hasExpired() {
if (expires == null) {
return false;
}
Date now = new Date();
return now.after(expires);
}
public String toString() {
StringBuilder result = new StringBuilder(name);
result.append("=");
result.append(value);
return result.toString();
}
Äí۰¡ ¸¸·áµÈ °æ¿ì¿¡´Â ¡®match¡¯°¡ Ç¥½ÃµÇ¸é ¾È µÈ´Ù.
public boolean matches(URI uri) {
if (hasExpired()) {
return false;
}
String path = uri.getPath();
if (path == null) {
path = "/";
}
return path.startsWith(this.path);
}
¾Æ·¡´Â Àüü
import java.net.*;
import java.text.*;
import java.util.*;
public class Cookie {
String name;
String value;
URI uri;
String domain;
Date expires;
String path;
private static DateFormat expiresFormat1
= new SimpleDateFormat("E, dd MMM yyyy k:m:s 'GMT'", Locale.US);
private static DateFormat expiresFormat2
= new SimpleDateFormat("E, dd-MMM-yyyy k:m:s 'GMT'", Local.US);
/**
* Construct a cookie from the URI and header fields
*
* @param uri URI for cookie
* @param header Set of attributes in header
*/
public Cookie(URI uri, String header) {
String attributes[] = header.split(";");
String nameValue = attributes[0].trim();
this.uri = uri;
this.name =
nameValue.substring(0, nameValue.indexOf('='));
this.value =
nameValue.substring(nameValue.indexOf('=')+1);
this.path = "/";
this.domain = uri.getHost();
for (int i=1; i < attributes.length; i++) {
nameValue = attributes[i].trim();
int equals = nameValue.indexOf('=');
if (equals == -1) {
continue;
}
String name = nameValue.substring(0, equals);
String value = nameValue.substring(equals+1);
if (name.equalsIgnoreCase("domain")) {
String uriDomain = uri.getHost();
if (uriDomain.equals(value)) {
this.domain = value;
} else {
if (!value.startsWith(".")) {
value = "." + value;
}
uriDomain = uriDomain.substring(
uriDomain.indexOf('.'));
if (!uriDomain.equals(value)) {
throw new IllegalArgumentException(
"Trying to set foreign cookie");
}
this.domain = value;
}
} else if (name.equalsIgnoreCase("path")) {
this.path = value;
} else if (name.equalsIgnoreCase("expires")) {
try {
this.expires = expiresFormat1.parse(value);
} catch (ParseException e) {
try {
this.expires = expiresFormat2.parse(value);
} catch (ParseException e2) {
throw new IllegalArgumentException(
"Bad date format in header: " + value);
}
}
}
}
}
public boolean hasExpired() {
if (expires == null) {
return false;
}
Date now = new Date();
return now.after(expires);
}
public String getName() {
return name;
}
public URI getURI() {
return uri;
}
/**
* Check if cookie isn't expired and if URI matches,
* should cookie be included in response.
*
* @param uri URI to check against
* @return true if match, false otherwise
*/
public boolean matches(URI uri) {
if (hasExpired()) {
return false;
}
String path = uri.getPath();
if (path == null) {
path = "/";
}
return path.startsWith(this.path);
}
public String toString() {
StringBuilder result = new StringBuilder(name);
result.append("=");
result.append(value);
return result.toString();
}
}
ÀÌÁ¦ Á¶°¢µéÀÌ ¸ðµÎ È®º¸µÇ¾úÀ¸¹Ç·Î ¾ÕÀÇ
>> java Fetch http://java.sun.com
Cookies: {Connection=[keep-alive], Host=[java.sun.com],
User-Agent=[Java/1.5.0_04], GET / HTTP/1.1=[null],
Content-type=[application/x-www-form-urlencoded],
Accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2]}
Cache: []
Adding to cache: SUN_ID=192.168.0.1:235411125667328
Cookies: {Connection=[keep-alive], Host=[java.sun.com],
User-Agent=[Java/1.5.0_04], GET / HTTP/1.1=[null],
Cookie=[SUN_ID=192.168.0.1:235411125667328],
Content-type=[application/x-www-form-urlencoded],
Accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2]}
Cache: [SUN_ID=192.168.0.1:235411125667328]
(À§¿¡ Ç¥½ÃµÈ °á°ú¿¡¼ ±ä ÇàÀº ¼öµ¿À¸·Î ÁٹٲÞÇÑ °ÍÀÓ)
¡®Cache¡¯·Î ½ÃÀ۵Ǵ ÇàÀº ÀúÀåµÈ ij½Ã¸¦ ³ªÅ¸³½´Ù. ÀúÀåµÈ Äí۰¡ Áï½Ã ¹ÝȯµÇÁö ¾Êµµ·Ï
ÄíŰ¿Í URL Á¢¼ÓÀ» ÀÌ¿ëÇÑ ÀÛ¾÷¿¡ °üÇØ ÀÚ¼¼È÷ ¾Ë°í ½ÍÀ¸¸é ÀÚ¹Ù Æ©Å丮¾óÀÇ Custom Networking trail(¿µ¹®)À» ÂüÁ¶ÇÒ °Í. ÀÌ´Â J2SE 1.4¿¡ ±â¹ÝÀ» µÎ°í ÀÖÀ¸¹Ç·Î Æ©Å丮¾ó¿¡´Â ¾ÆÁ÷ ¿©±â¼ ¼³¸íÇÑ |
||
| Å×Å©ÆÁ ÄûÁî Á¤´ä | ||
|
Áö³ ÁÖ ´º½º·¹ÅÍ·Î ¹ß¼ÛµÇ¾ú´ø Å×Å©ÆÁ ÄûÁîÀÇ Á¤´äÀ» ¾Ë·Áµå¸³´Ï´Ù. Âü¿©ÇØÁֽЏðµç ºÐ²² °¨»çµå¸®¸ç, ´ç÷ÀÚ´Â 10¿ù 26ÀÏ SKDN ȨÆäÀÌÁö¿¡¼ ¹ßÇ¥ÇÕ´Ï´Ù.
|
||
º»
¸ÞÀÏÀº ¼ö½ÅÀ» µ¿ÀÇÇÑ È¸¿ø´Ô¿¡°Ô¸¸ ¹ß¼ÛµË´Ï´Ù.
º» ¸ÞÀÏÀÇ ¼ö½ÅÀ» °ÅºÎÇϰųª ¼ö½ÅÁÖ¼Ò¸¦ º¯°æÇÏ·Á¸é SKDN@Sun.comÀ¸·Î ¹®ÀÇ Áֽñ⠹ٶø´Ï´Ù. SKDN(Sun Korea Developers Network)¿¡¼ J2EE/J2SE Å×Å©ÆÁ µî ´Ù¾çÇÑ ¾ÆÆ¼Å¬µéÀ» Âü°íÇϼ¼¿ä. Copyright 2003-2005 Sun Korea, Ltd. All rights reserved. |