سؤال

I am writing a webserver, and I need to set a cookie on the client's web browser. I get a OutputStream through Socket.getOutputStream(), but I cannot find a way to send a header with it. I tried sending javascript code to set the cookie on the client side, but the cookies set that way are not being sent back to the server. How can I set a cookie through the header/other way.

هل كانت مفيدة؟

المحلول

You send the response header right before the body:

PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println("HTTP/1.0 200 Ok");
writer.println("Set-Cookie key=value Max-Age=8640");
writer.println("Content-Type text/html");
writer.println()//important
//send your body here
writer.flush();//send message

Here's a list of HTTP response header fields https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top