【问题标题】:Java setting cookies through stream [closed]Java通过流设置cookie [关闭]
【发布时间】:2014-05-03 15:27:31
【问题描述】:

我正在编写一个网络服务器,我需要在客户端的网络浏览器上设置一个 cookie。 我通过 Socket.getOutputStream() 获得了一个 OutputStream,但我找不到用它发送标头的方法。我尝试发送 javascript 代码以在客户端设置 cookie,但以这种方式设置的 cookie 不会被发送回服务器。 如何通过标头/其他方式设置cookie。

【问题讨论】:

标签: java sockets cookies


【解决方案1】:

您在正文之前发送响应标头:

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

这里是 HTTP 响应头字段列表https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 2011-08-25
    • 2013-12-29
    • 1970-01-01
    • 2021-08-25
    • 2012-02-17
    • 1970-01-01
    • 2015-10-17
    • 2011-05-16
    相关资源
    最近更新 更多