问题描述
||
我正在用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的具体实现。但是,它只是拒绝为我工作,我在做什么错?
解决方法
在检查cookie存储区之前,您需要阅读HTTP标头字段,并且调用ѭ1不会读取HTTP标头。请参阅javadoc的前几行。
如果在处理过程中需要cookie,则调用
getInputStream()
会连接并解析标头字段,URLConnection中的其他一些方法也会如此。