【问题标题】:HttpRequestHandler - How to tell client to save a cookie?HttpRequestHandler - 如何告诉客户端保存 cookie?
【发布时间】:2015-12-28 08:59:42
【问题描述】:

我正在使用 Java 制作一个简单的HTTP 服务器,用于教育目的。我需要知道如何指示客户端保存 cookie 以识别其会话 ID。

我已经完成了我的研究,偶然发现了 thisthis,尽管它们提供了很多信息并且实际上向我介绍了整个 CookieStore 事情,但并没有真正指定如何告诉客户保存饼干。

据我了解,HttpRequestHandlers 中的handle 方法只传递了三个参数:

  • HttpRequest - 请求本身以及一些相关信息。
  • HttpResponse - 应在其中写入响应的“媒介”。
  • HttpContext - ...(不太清楚它的作用,TBH。)

同时,我上面提到的链接中的所有答案都会调用

  • response = client.execute(httppost, localContext);,或
  • HttpResponse response1 = httpClient.execute(method1, httpContext);

..在处理的某个时刻。我不知道如何获得对客户端的引用(从而执行存储 cookie 的请求)。

我该怎么办?我错过了什么吗?

【问题讨论】:

  • 当您的服务器响应客户端的请求时,您必须在该响应中包含 cookie 标头(例如,Set-Cookie: value;path;domain;expire

标签: java apache http


【解决方案1】:
Cookie userCookie = new Cookie("Name","Value");
userCookie.setMaxAge(-1);//for a session cookie
userCookie.setPath("/");
response.addCookie(userCookie);//adds to cookie to the response that is sent to the browser.

【讨论】:

  • 这看起来像。当我回到家时,我会试一试,并验证它是否确实回答了我的问题。非常感谢!
  • 很抱歉,我试过之后,addCookie 方法只在HttpServletResponse 中可用,在我目前使用的HttpResponse 中不可用。
  • 有趣。您将需要在响应标头中添加一个“Set-Cookie:”元素。您为 HttpResponse 对象使用什么库?
  • 我目前正在使用 Apache。也许重要的是要注意我正在使用 Android。所以我认为 Apache 是唯一的出路。
  • 看看那个库,HttpResponse 扩展了 HttpMessage。 HttpMessage 操作标头。尝试类似 response.addHeader("Set-Cookie","value;path;domain;expire);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2020-08-04
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
相关资源
最近更新 更多