Problems getting the correct cookie in Java

When I receive cookies in my Java servo, all values ​​from getPath () are null.

So, if a cookie with the same name is set in the / foo directory, and in the root directory, I get two cookies with the same exact name, but I cannot tell them apart because getPath () returns null for both.

I looked in firebug and saw that firefox was not sending anything along the way.

My application uses a "memme" cookie whose path is set to "/". Everything works fine as long as there is only one cookie named memme. But if some other cookie gets the same name on a different path, for example / foo, then my application won't know which one I have set for the root.

How can I tell the difference between cookies? Do I need to worry about one name with the same name in the subdirectory, or can I assume that there will only be one that I set?

+2


a source to share


3 answers


If the browser does not send the path, you must set the path to "/" in your cookie handler.



The server sets the cookies, not the web browser, so if you set all the cookie paths you created for "/" for the same domain, you don't need to worry about that.

+2


a source


I'm not sure how much this will help you, but I recently wrote this method to retrieve cookies from a URLConnection object and return them as a string:

public String getCookies(URLConnection connection) {
    String headerName = null;
    String cookie = "";
    for (int i=1; (headerName = connection.getHeaderFieldKey(i))!=null; i++) {
        if (headerName.equals("Set-Cookie")) {
            if (cookie.equals("")) {
                cookie = connection.getHeaderField(i);
            }
            else {
                cookie = cookie + "; " + connection.getHeaderField(i);
            }
        }
    }
    writeToCookiesFile(cookie);
    return cookie;
}

      



This method was only used in a simple application though :) Hope it will be useful!

0


a source


The browser will only send the cookies defined for path / foo when the URL path starts with / foo. If a cookie with the same name is set on both / and foo, there is no way to tell them apart.

0


a source







All Articles