如何在Java中访问/保存cookie
我正在用 Java 编写一些软件。
我正在测试 cookie 管理功能,但我似乎无法让 cookie 工作。我编写了一个快速的 PHP 来删除 cookie,并在浏览器中测试了它,并且 cookie 正常删除。
不过,请看一下这段代码:
CookieManager cManager = new CookieManager();
CookieHandler.setDefault(cManager);
try
{
URL url = new URL("http://localhost/_techfactory/apage.php");
URLConnection connection = url.openConnection();
CookieStore cookieJar = cManager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
for ( HttpCookie cookie : cookies)
{
System.out.print(cookie);
}
Boolean isittrue = cookies.isEmpty();
System.out.print(isittrue);
BufferedReader bin = new BufferedReader ( new InputStreamReader(connection.getInputStream()));
String line;
while ( ( line = bin.readLine()) != null )
System.out.print(line);
}
catch ( Exception e )
{
System.out.println(e);
}
虽然语法上是正确的,但除了页面中的 HTML 之外,它不会输出任何内容。现在大家都认为,CookieManager 实现是 CookieHandler、CookiePolicy 和 CookieStore 的具体实现。然而,它只是拒绝为我工作,我做错了什么?
I am writing some software in Java.
I am testing the cookie managment functionality but I can't seem to get cookies working. I wrote a quick PHP that drops a cookie, and I tested that in my browser and the cookie drops fine.
However, take a look at this code:
CookieManager cManager = new CookieManager();
CookieHandler.setDefault(cManager);
try
{
URL url = new URL("http://localhost/_techfactory/apage.php");
URLConnection connection = url.openConnection();
CookieStore cookieJar = cManager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
for ( HttpCookie cookie : cookies)
{
System.out.print(cookie);
}
Boolean isittrue = cookies.isEmpty();
System.out.print(isittrue);
BufferedReader bin = new BufferedReader ( new InputStreamReader(connection.getInputStream()));
String line;
while ( ( line = bin.readLine()) != null )
System.out.print(line);
}
catch ( Exception e )
{
System.out.println(e);
}
This, although being syntactically correct, doesn't output anything, except the HTML from the page. Now by all accounts, the CookieManager implementaiton is a concrete implementation of CookieHandler, CookiePolicy and CookieStore. However, it just refuses to work for me, what I am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在检查 cookie 存储之前,您需要读取 HTTP 标头字段,并且调用
openConnection()
不会读取 HTTP 标头。请参阅 javadoc。如果您在处理过程中需要 cookie,请调用 getInputStream() 来连接并解析标头字段,URLConnection 中的其他一些方法也是如此。
You need to read the HTTP header fields before checking the cookie store, and calling
openConnection()
does not read the HTTP headers. See the first few lines of the javadoc.If you need the cookies during processing, calling
getInputStream()
connects and parses the header fields, as will some of the other methods in URLConnection.