0

I'm in a journey of making a simple HTTP server using Java for educational purposes. I need to know how to instruct a client to save a cookie for identifying its session ID.

I've done my research and stumbled upon this and this which, despite being greatly informative and in fact introduced me to the whole CookieStore thing, does not really specify how to tell the client to save a cookie.

From what I've come to understand, the handle method in HttpRequestHandlers has only three parameter passed to it:

  • HttpRequest - the request itself along with some information about it.
  • HttpResponse - the "medium" as of where the response should be writen upon.
  • HttpContext - ... (Not really sure what it does, TBH.)

Meanwhile, all of the answers in the links I've stated above would call

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

..at some point of the handling. I've no idea on how one could get a reference to the client (and thus execute the request to store the cookie).

What should I do? Am I missing something?

Community
  • 1
  • 1
Hadi Satrio
  • 4,272
  • 2
  • 24
  • 45
  • When your's server gives response to client's request, you must include cookie headers (like, `Set-Cookie: value;path;domain;expire`) in that response – ankhzet Sep 30 '15 at 14:20

1 Answers1

0
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.
Angus
  • 128
  • 2
  • 9
  • This would seem like it. I'm going to give it a go when I got home and verify if it indeed answer my question. Thanks a lot! – Hadi Satrio Sep 30 '15 at 18:09
  • I'm sorry but after I tried it, the `addCookie` method only available in `HttpServletResponse` and not in `HttpResponse` I'm currently using. – Hadi Satrio Oct 01 '15 at 04:41
  • Interesting. You are going to need to add a "Set-Cookie:" element to your response headers. What library are you using for the HttpResponse object? – Angus Oct 02 '15 at 15:16
  • I'm going through with Apache at the moment. Perhaps it's important to notice that I'm working on Android. So I think Apache is the only way to go. – Hadi Satrio Oct 02 '15 at 15:21
  • Looking at that library, HttpResponse extends HttpMessage. HttpMessage manipulates the header. Try something like response.addHeader("Set-Cookie","value;path;domain;expire); – Angus Oct 02 '15 at 15:23
  • I guess that'll do! Was hoping for a more sophisticated solution but after spending some time scouring the docs it seems like the only way to go. Thanks for pointing it out for me. :) – Hadi Satrio Oct 02 '15 at 15:30