Java的CookieManager

本文介绍了Java如何管理和处理HTTPCookie,包括使用CookieHandler和CookieManager类来存储和获取Cookie,以及通过CookiePolicy控制接受哪些Cookie。此外,还详细讲解了CookieStore接口,用于在本地存储和操作Cookie。
摘要由CSDN通过智能技术生成

1. 简介

Java5包括一个抽象类Java.net.CookieHandler,它定义了存储和获取Cookie的一个API,但不包括这个抽象类的实现,所以还有很多工作要做。Java6进一步作了补充,为CookieManager增加了一个可以使用的具体子类java.net.CookieManager。不过默认情况下Cookie并不打开。在Java存储和返回Cookie之前,需要先启动cookie

CookieManager manager=new CookieManager();
CookieManager.setDefault(manager)

用这两行代码安装一个CookieManager之后,对于你用URL类连接的HTTP服务器,Java会存储这些服务器发送的所有Cookie,在后续的请求中向这些服务器发回所存储的cookie,不过,对于接受哪里发送的Cookie,可以通过指定一个CookiePolicy来做到

  • CookiePolicy.ACCEPT_ALL接受所有的cookie
  • CookiePolicy.ACCEPT_NONE不接受任何cookie
  • CookiePolicy.ACCEPT_ORIFINAL_SERVER值接受一方的cookie

下面这段代码只接受一方的cookie,而会阻塞第三方的cookie(即只接受与你对话的服务器发送的cookie,而不接受Internet上其它服务器发送的cookie):

CookieManager manager=new CookieManager();
manager.setCoolkiePolicy(CookiePolicy.AACCEPT_ORIFINAL_SERVER);
CookieHandler.setDefault(manager)

下面这段代码我们自行实现了CookiePolicy接口,并覆盖了shouldAccept()方法:

public class NoGovermentCoolies implements CookiePolicy{
	@Override
	public boolean shouldAccept(URI uri,HttpCookie cookie){
	   if(uri.getAuthority().toLowerCase().endWith(".gov") || cookie.getDomain().toLowerCase().endWith(".gov")){
	    return false;
	   }
	   return true;
	}
}

2. CookieStore

有时有必要在本地存放和获取Cookie。一个应用退出时,可以把cookie库保存在磁盘上,下一次启动时再加载这些cookie。可以用getCookieStore()方法获取这个cookie库,CookieManager就在这里保存它的cookie

CookieStore store=manager.getCookieStore()

CookieStore类允许你增加,删除和列出cookie,使你能控制在正常HTTP请求和响应流之外发送的cookie

public void add(URI uri, HttpCookie cookie)
public List<HttpCookie> get(URI uri)
public List<HttpCookie> getCookies()
public List<URI> getURIs()
public boolean remove(URI uri,HttpCookie cookie)
public boolean removeAll()
  • public void add(URI uri, HttpCookie cookie)

将一个 HTTP cookie 添加到存储区。每个传入的 HTTP 响应都会调用此函数。要存储的 Cookie 可能与 URI 相关联,也可能不关联。如果它不与 URI 关联,则 Cookie 的域和路径属性将指示它的来源。如果它与 URI 相关联,并且未指定其域和路径属性,则给定 URI 将指示此 cookie 的来源。如果与给定 URI 对应的 cookie 已经存在,则将其替换为新的 cookie。

public class QuizCardBuilder {
    public static void main(String[] args) {
        try {
            URL u=new URL("http://www.baidu.com");
            //创建socket连接指定的网站
            URLConnection uc=u.openConnection();
            //创建一个CookieManager对象
            CookieManager cookieManager=new CookieManager();
            //设置接受cookie的范围(只接受百度服务器发送过来的)
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
            CookieHandler.setDefault(cookieManager);
            CookieStore store=cookieManager.getCookieStore();
            URI uri=u.toURI();
            //新建一个cookie
            HttpCookie cookie=new HttpCookie("skin","noskin");
            store.add(uri,cookie);
            System.out.println(store.get(uri));
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

在这里插入图片描述

  • public List<HttpCookie> get(URI uri)
public class QuizCardBuilder {
    public static void main(String[] args) {
        try {
            URL u=new URL("http://www.baidu.com");
            //创建socket连接指定的网站
            URLConnection uc=u.openConnection();
            //创建一个CookieManager对象
            CookieManager cookieManager=new CookieManager();
            //设置接受cookie的范围(只接受百度服务器发送过来的)
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
            CookieHandler.setDefault(cookieManager);
            CookieStore store=cookieManager.getCookieStore();
            URI uri=u.toURI();
            //新建一个cookie
            HttpCookie cookie=new HttpCookie("skin","noskin");
            store.add(uri,cookie);
            System.out.println(store.get(uri).toString());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}
  • public boolean remove(URI uri,HttpCookie cookie)
public class QuizCardBuilder {
    public static void main(String[] args) {
        try {
            URL u=new URL("http://www.baidu.com");
            //创建socket连接指定的网站
            URLConnection uc=u.openConnection();
            //创建一个CookieManager对象
            CookieManager cookieManager=new CookieManager();
            //设置接受cookie的范围(只接受百度服务器发送过来的)
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
            CookieHandler.setDefault(cookieManager);
            CookieStore store=cookieManager.getCookieStore();
            URI uri=u.toURI();
            //新建一个cookie
            HttpCookie cookie=new HttpCookie("skin","noskin");
            store.add(uri,cookie);
            System.out.println(store.get(uri).toString());
            System.out.println(store.remove(uri,cookie));
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}
以下是一个使用Java模拟登陆的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.List; import java.util.Map; public class LoginDemo { public static void main(String[] args) throws Exception { String loginUrl = "http://example.com/login"; String username = "your_username"; String password = "your_password"; // Create a new URL object URL url = new URL(loginUrl); // Create a new HttpURLConnection object HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set the request method to POST connection.setRequestMethod("POST"); // Set the request headers connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Set the request parameters String params = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); connection.setDoOutput(true); connection.getOutputStream().write(params.getBytes("UTF-8")); // Send the request int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Read the response BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print the response System.out.println(response.toString()); // Get the cookies from the response headers Map<String, List<String>> headerFields = connection.getHeaderFields(); List<String> cookiesHeader = headerFields.get("Set-Cookie"); if (cookiesHeader != null) { // Parse the cookies and store them in a CookieManager object java.net.CookieManager cookieManager = new java.net.CookieManager(); for (String cookie : cookiesHeader) { cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0)); } // Use the CookieManager to send subsequent requests with the cookies URL newUrl = new URL("http://example.com/protected_page"); HttpURLConnection newConnection = (HttpURLConnection) newUrl.openConnection(); cookieManager.getCookieStore().getCookies().forEach(c -> newConnection.addRequestProperty("Cookie", c.toString())); int newResponseCode = newConnection.getResponseCode(); if (newResponseCode == HttpURLConnection.HTTP_OK) { // Read the response BufferedReader newIn = new BufferedReader(new InputStreamReader(newConnection.getInputStream())); String newInputLine; StringBuffer newResponse = new StringBuffer(); while ((newInputLine = newIn.readLine()) != null) { newResponse.append(newInputLine); } newIn.close(); // Print the response System.out.println(newResponse.toString()); } else { System.out.println("Failed to fetch protected page"); } } } else { System.out.println("Failed to login"); } } } ``` 此代码将使用POST请求发送用户名和密码到登录页面。如果登录成功,它将获取响应标头中的cookie,并将其存储在CookieManager对象中。然后,它将使用CookieManager对象向受保护的页面发送新请求,并在请求中添加所有cookie。如果此请求成功,它将打印受保护页面的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值