我目前正在尝试从我的 Java 桌面应用程序中读取某个 cookie。我使用了 chrome 扩展程序来创建 cookie,并使用 chrome 控制台我可以看到它已经创建并且具有正确的值。
当我尝试从我的 Java 应用程序中读取它时,问题就出现了,我当前的代码获得了 3 个看似随机的 cookie,如果它包含我的,这不会是一个问题。我已经确保我的 cookie 不仅是主机而且它不安全,它实际上具有与其他 3 个相同的属性,但它只是没有被返回。
这是我当前的代码:
Java 应用程序代码:
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Spud
*/
public class Reading_My_Created_Cookie
{
/**
* @param args the command line arguments
*/
private static final String SEARCH_TERM = "Tab";
private static final String ADDRESS = "http://www.youtube.com/";
private static final CookieManager COOKIEMANAGER = new CookieManager();
private static Object myCookie;
public static void main(String[] args)
{
try
{
COOKIEMANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(COOKIEMANAGER);
URL url = new URL(ADDRESS);
URLConnection connection = url.openConnection();
connection.getContent();
CookieStore cookieStore = COOKIEMANAGER.getCookieStore();
Object[] cookieJar = cookieStore.getCookies().toArray();
for (int i = 0; i < cookieJar.length; ++i)
{
System.out.println(cookieJar[i]);
}
//myCookie = checkForCookie(cookieJar);
//System.out.println(myCookie);
}
catch (IOException ex)
{
Logger.getLogger(Reading_My_Created_Cookie.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Object checkForCookie(Object[] cookieJar)
{
for (int i = 0; i < cookieJar.length; ++i)
{
if (cookieJar[i].equals(SEARCH_TERM))
{
return cookieJar[i];
}
}
return "Cookie not found";
}
}
这当前输出以下内容:
run:
YSC=6EIDrzvf02s
PREF=f1=50000000
VISITOR_INFO1_LIVE=qKCoNVZQMi8
BUILD SUCCESSFUL (total time: 4 seconds)
对于任何想要它的人,这是我当前的扩展 JavaScript 代码:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
alert("cookieName = " + cookieName + " cookieValue/tabTitle = " + cookieValue + " tabURL = " + cookieURL);
}
感谢您抽出宝贵时间,我真的希望我能把它整理好,因为它目前是我 A 级计算项目的关键部分。