【问题标题】:Apache Http Components - setting cookieApache Http 组件 - 设置 cookie
【发布时间】:2016-03-07 04:03:41
【问题描述】:

我正在使用 Apache Http 组件为 localhost 设置一个 cookie。当我返回 cookie 时,我得到了输出:

[version: 0][name: testCookie][value: test][domain: http://localhost:9090/][path: /][expiry: Mon Aug 07 19:11:56 BST 2017]

这让我觉得 cookie 已经设置好了,但是当我在 chrome 中检查它是否在 chrome://settings/cookies 中时,那里什么都没有。

    public Object makeCookie(String p) throws IOException, MalformedCookieException{

        Calendar myCal = Calendar.getInstance();
        myCal.set(2017, 07, 07);
        Date theDate = myCal.getTime();
        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("testCookie",p);
        // Set effective domain and path attributes
        cookie.setDomain("http://localhost:9090/");
        cookie.setPath("/");
        cookie.setExpiryDate(theDate);
        cookieStore.addCookie(cookie);
        // Set attributes exactly as sent by the server
        cookie.setAttribute(ClientCookie.PATH_ATTR, "/");
        cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "http://localhost:9090/");
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();

        return cookie;
}

我已经坚持了好几个小时了,我只是想不通为什么它没有被存储在浏览器中

【问题讨论】:

    标签: java apache http cookies


    【解决方案1】:

    实际上,您的代码只是创建客户端 cookie 存储,但不会将创建的 cookie 发送到任何地方。

    根据维基百科 (https://en.wikipedia.org/wiki/HTTP_cookie),“cookie 是从网站发送的一小段数据,并在用户浏览时存储在用户的网络浏览器中。”

    HttpClient 不是您需要的实体,因为它是客户端,而不是服务器。您可以使用它来执行对网站的 HTTP 请求,但它只是消费者,就像您的本地浏览器一样。因此,即使您在客户端上指定 cookie 存储,它对您的本地浏览器也没有影响。服务器(比如网站)是向客户端发送 cookie 的人。

    代码中的 HttpClient 和本地浏览器是 2 个独立的客户端。他们可以从网站接收 cookie,但这两个客户端本身并不是网站。这就是为什么 CloseableHttpClient 对象在这里没用。此外,您不会在代码中使用它。此外,它可能会泄漏内存,因为您没有正确关闭它。

    正如我已经说过的,您的代码只是创建了 cookie。因此,您需要将创建的 cookie 发送给客户端。你甚至不需要创建cookie存储,你可以自己创建cookie。

    因此您需要使用 Servlet API 创建一个简单的 Web 应用程序。然后,您可以将创建的 cookie 附加到所需 HTTP 请求处理程序中的 HttpServlerResponse 对象。你可以这样做(SpringMVC 示例):

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html")
        public String index(HttpServletResponse response) {
            // no prepareCookie implementation here
            Cookie myCookie = prepareCookie();
            response.addCookie(myCookie);
            // view name
            return "index";
        }
    

    【讨论】:

    • 感谢您的回复。问题是,我使用的是 nanohttp(一个轻量级服务器),谁的 cookie 不提供设置路径的方法。这就是为什么我不想使用 servlet API 并试图找到另一种传递 cookie 的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2021-12-19
    相关资源
    最近更新 更多