Java by API/java.net/CookieManager

Материал из Java эксперт
Версия от 14:16, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

CookieManager: getCookieStore()

  
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 Main {
  public static void main(String args[]) throws Exception {
    String urlString = "http://java.sun.ru";
    CookieManager manager = new CookieManager();
    CookieHandler.setDefault(manager);
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    Object obj = connection.getContent();
    url = new URL(urlString);
    connection = url.openConnection();
    obj = connection.getContent();
    CookieStore cookieJar = manager.getCookieStore();
    List<HttpCookie> cookies = cookieJar.getCookies();
    for (HttpCookie cookie : cookies) {
      System.out.println(cookie);
    }
  }
}





CookieManager: setCookiePolicy(CookiePolicy cookiePolicy)

  

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.URL;
import java.util.List;
public class Main {
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("usage: java ListAllCookies url");
      return;
    }
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cm);
    new URL(args[0]).openConnection().getContent();
    List<HttpCookie> cookies = cm.getCookieStore().getCookies();
    for (HttpCookie cookie : cookies) {
      System.out.println("Name = " + cookie.getName());
      System.out.println("Value = " + cookie.getValue());
      System.out.println("Lifetime (seconds) = " + cookie.getMaxAge());
      System.out.println("Path = " + cookie.getPath());
      System.out.println();
    }
  }
}