简体   繁体   中英

Java cookies using URLConnection

I have a method that creates a cookie for localhost:9090/application.

public Object makeCookie(String p) throws IOException{

        URL myUrl = new URL("localhost:9090/application");
        URLConnection urlConn = myUrl.openConnection();

        urlConn.setRequestProperty("testCookie", p);
        urlConn.connect();

        return urlConn;
    }

I have a method that should print the name and domain of the cookie I just set, but I am getting no results.

CookieManager cookieManager;
     URL url;
     URLConnection connection;
     CookieStore cookieStore;
     List<HttpCookie> cookieList;
public boolean checkone (String test1) throws ClassNotFoundException, IOException{
         cookieManager = new CookieManager();
         CookieHandler.setDefault(cookieManager);
         url = new URL("localhost:9090/application/");
         connection = url.openConnection();
         connection.getContent();
         cookieStore = cookieManager.getCookieStore();

         cookieList = cookieStore.getCookies();
         for (HttpCookie cookie: cookieList){

             System.out.println("Domain: " + cookie.getDomain());
             System.out.println("name of cookie: " + cookie.getName());

         }
         return true;       

     }

Am I missing something when creating the cookie?

I do not think you are getting the cookies the right way. The cookies are set in the headers of the request. I do not see that in your example. Take a look at this:

https://examples.javacodegeeks.com/core-java/net/urlconnection/get-cookies-from-http-connection/

Take a look at this also:

How to set Cookies at Http Get method using Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM