如何使用Java从网站获取所有cookie



我想使用Java从网站获取所有cookie在cookie中有:

  • _ga
  • _gid
  • PHPSESSID

我试过这个代码,但它只给出了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);
}

我该如何解决这个问题?

上面给出的代码示例正在建立到特定网站(example.com(的URL连接

因此,对cookieManager的调用将仅产生特定网站(example.com(设置的cookie。它不会读取其他网站创建的cookie。

为了获取所有cookie,必须更新程序,以便将URL连接到创建cookie所涉及的所有网站。

下面是一个工作示例:

// 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/");
} 
} 

输出:

> 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

相关内容

  • 没有找到相关文章

最新更新