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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With