【问题标题】:Java cookies using URLConnection使用 URLConnection 的 Java cookie
【发布时间】:2016-06-20 01:29:38
【问题描述】:

我有一个为 localhost:9090/application 创建 cookie 的方法。

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;
    }

我有一个方法可以打印我刚刚设置的 cookie 的名称和域,但我没有得到任何结果。

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;       

     }

我在创建 cookie 时是否遗漏了什么?

【问题讨论】:

    标签: java http cookies


    【解决方案1】:

    我认为您获取 cookie 的方式不正确。 cookie 设置在请求的标头中。我在您的示例中没有看到这一点。看看这个:

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

    也看看这个:

    How to set Cookies at Http Get method using Java

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2015-06-25
      • 2012-11-05
      • 2014-10-29
      相关资源
      最近更新 更多