簡體   English   中英

Java Applet-刪除/忽略所有cookie(JSoup)

[英]Java applet - delete/ignore all cookies (JSoup)

我編寫了一個Java小程序,它可以從單個主機的多個頁面中獲取HTML內容,並從中提取數據。 我使用的是Jsoup,它運行良好,但是它會自動在瀏覽器中對該主機集使用cookie,並在后續請求中發送新設置的cookie。 (我相信這是由Java本地完成的)

我希望它在運行小程序時忽略服務器設置的所有cookie,並忽略瀏覽器可能已經具有的所有cookie。

我的代碼很簡單。

String url = "http://example.com/my/web-page.html";
Document document = Jsoup.connect(url).userAgent("<hard-coded static value>").get();
// Extract data from document with org.Jsoup.nodes.Document.select(), etc.

重復多個URL,每個URL具有相同的主機(example.com)。

總而言之,我基本上希望它:

  1. 忽略example.com中可能在瀏覽器中設置的任何cookie。
  2. 如果在applet發出請求時服務器設置了任何新的cookie,則對於后續請求將忽略它。 如果可能,也阻止cookie被存儲在瀏覽器中。

我已經搜索了很多,卻找不到解決方案。 非常感謝您的幫助。 我不介意使用Apache HTTPClient或任何其他第三方庫,但我不想這樣做,這樣可以使applet的文件大小保持較小。

在此先感謝一噸:)

您應該為此操作org.jsoup.Connection.Request

    String url = "http://example.com/my/web-page.html";
    Connection con = Jsoup.connect(url).userAgent("<hard-coded static value>");
    ...
    con.get();
    ...
    Request request = con.request();
    Map<String, String> cookies = request.cookies();
    for(String cookieName : cookies.keySet()) {
        //filter cookies you want to stay in map
        request.removeCookie(cookieName);
    }

您還應該禁用followRedirects並手動進行重定向(刪除cookie)。 您將必須實現自己的“ Cookie /域刪除器”。

JSoup內部使用java.net.HttpURLConnection ,因此您無法以某種方式截獲org.jsoup.helper.HttpConnection.Response.execute(...)上實際調用execute方法的核心功能,因為它是靜態的並且具有程序包保護的訪問。 同樣,您不能在HttpConnection設置req (請求專用對象)和res (響應專用對象)。 而且,您無法實現自己的org.jsoup.Connection (或由於private構造函數而擴展了其實現HttpConnection ),因此強制JSoup使用它。

考慮到以上所有問題,我建議-使用HttpClient / HtmlUnit-因為您最終將在受限環境中最終“重新發明輪子”。

而不是使用Connection (從Jsoup.connect("url");方法返回的結果),請使用Response

Map<String, String> cookies = new HashMah<String, String>();

Response res = Jsoup
    .connect("url")
    .cookies(cookies)
    .userAgent("userAgent")
    .method(Method.GET) //Or whatever method needed be
    .execute();

我知道這是一條很大的路線,但那會很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM