简体   繁体   中英

How can I get all cookies from a website using Java

I want to get all cookies from a website using Java In cookie have:

  • _ga
  • _gid
  • PHPSESSID

I tried this code, but it just gave only PHPSESSID .

 CookieManager cookieManager = new CookieManager();
 CookieHandler.setDefault(cookieManager);

 URL url = new URL("https://example.com/");

 URLConnection connection = url.openConnection();
 connection.getContent();

 List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
 for (HttpCookie cookie : cookies) {
     System.out.println(cookie.getDomain());
     System.out.println(cookie);
 }

How can I solve this?

The code sample presented above is making a URL connection to specific site (example.com).

Therefore, the call to cookieManager will yield only the cookies set by the specific website (example.com) only. It will not read the cookie created by another website.

In order to fetch all cookies, the program must be updated to make URL connections to all the websites involved in creating the cookies.

Here is a working example:

// File name:  GetCookies.java

import java.io.*; 
import java.net.*; 

public class GetCookies { 

    public static void showCookies(String websiteURL)  throws IOException {
        CookieManager cookieManager = new CookieManager(); 
        CookieHandler.setDefault(cookieManager); 

        // Access the website
        URL url = new URL(websiteURL); 
        URLConnection urlConnection = url.openConnection(); 
        urlConnection.getContent();

        // Get CookieStore 
        CookieStore cookieStore = cookieManager.getCookieStore(); 

        // Get cookies 
        for (HttpCookie cookie : cookieStore.getCookies()) { 
            System.out.println("\n Cookie: " + cookie.getName()); 
            System.out.println("\t Domain: " + cookie.getDomain()); 
            System.out.println("\t Value: " + cookie.getValue());
        } 
    }
    public static void main(String[] args) throws IOException { 

        showCookies("https://stackoverflow.com/");
        showCookies("https://www.google.com/");
    } 
} 

Output:

> javac GetCookies.java

> java GetCookies

 Cookie: prov
         Domain: .stackoverflow.com
         Value: ece1201b-b714-98ef-c063-0015fcc6440b

 Cookie: NID
         Domain: .google.com
         Value: 200=Mhc_xgGU-7HFK243aESiUxBhUPOcsJ_eNiLSeQhrfA0   

 Cookie: 1P_JAR
         Domain: .google.com
         Value: 2020-03-22-01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM