Cookie cookie_id = new Cookie("username", value)
其中第一个参数是这个cookie保存的名字,第二个是cookie的值
返回用response的方法添加cookie,另外也可以设置最大生存时间,如果不设置代表关闭浏览器的时候cookie失效
response.addCookie(cookie_id)
这条语句是跳转到B页面response.setHeader("refresh", "1URL=B.jsp")
在B页面中,可以这么获得Cookie
Cookie[] username=request.getCookie()
这时cookie就在username变量中了,因为只有一个所以不用遍历,可以这样: out.println(username[1].getValue())
java设置cookie是通过 Servlet 设置的。通过 Servlet 设置 Cookies 包括三个步骤:
(1) 创建一个 Cookie 对象:您可以调用带有 cookie 名称和 cookie 值的 Cookie 构造函数,cookie 名称和 cookie 值都是字符串。
Cookie cookie = new Cookie("key","value")
请记住,无论是名字还是值,都不应该包含空格或以下任何字符:
[ ] ( ) = , " / ? @ :
(2) 设置最大生存周期:您可以使用 setMaxAge 方法来指定 cookie 能够保持有效的时间(以秒为单位)。下面将设置一个最长有效期为 24 小时的 cookie。
cookie.setMaxAge(60*60*24)
(3) 发送 Cookie 到 HTTP 响应头:您可以使用 response.addCookie 来添加 HTTP 响应头中的 Cookies,如下所示:
response.addCookie(cookie)
(4)完整实例:
// 导入必需的 java 库
import java.io.*
import javax.servlet.*
import javax.servlet.http.*
// 扩展 HttpServlet 类
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 为名字和姓氏创建 Cookies
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"))
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"))
// 为两个 Cookies 设置过期日期为 24 小时后
firstName.setMaxAge(60*60*24)
lastName.setMaxAge(60*60*24)
// 在响应头中添加两个 Cookies
response.addCookie( firstName )
response.addCookie( lastName )
// 设置响应内容类型
response.setContentType("text/htmlcharset=UTF-8")
PrintWriter out = response.getWriter()
String title = "设置 Cookies 实例"
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n"
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>名字</b>:"
+ request.getParameter("first_name") + "\n</li>" +
" <li><b>姓氏</b>:"
+ request.getParameter("last_name") + "\n</li>" +
"</ul>\n" +
"</body></html>")
}
}
你可以自定义一个RequestIntercaptor:String cookieKey = ...
String cookieValue = ...
RestAdapter adapter = new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
// assuming `cookieKey` and `cookieValue` are not null
request.addHeader("Cookie", cookieKey + "=" + cookieValue)
}
})
.setServer("http://...")
.build()
YourService service = adapter.create(YourService.class)
从服务器读取cookies再交给cookie manager管理:
OkHttpClient client = new OkHttpClient()
CustomCookieManager manager = new CustomCookieManager()
client.setCookieHandler(manager)
RestAdapter adapter = new RestAdapter.Builder()
.setClient(new OkClient(client))
...
.build()
CustomeCookieManager如下:
public class CustomCookieManager extends CookieManager {
// The cookie key we're interested in.
private final String SESSION_KEY = "session-key"
/**
* Creates a new instance of this cookie manager accepting all cookies.
*/
public CustomCookieManager() {
super.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
}
@Override
public void put(URI uri, Map<String, List<String>>responseHeaders) throws IOException {
super.put(uri, responseHeaders)
if (responseHeaders == null || responseHeaders.get(Constants.SET_COOKIE_KEY) == null) {
// No cookies in this response, simply return from this method.
return
}
// Yes, we've found cookies, inspect them for the key we're looking for.
for (String possibleSessionCookieValues : responseHeaders.get(Constants.SET_COOKIE_KEY)) {
if (possibleSessionCookieValues != null) {
for (String possibleSessionCookie : possibleSessionCookieValues.split("")) {
if (possibleSessionCookie.startsWith(SESSION_KEY) &&possibleSessionCookie.contains("=")) {
// We can safely get the index 1 of the array: we know it contains
// a '=' meaning it has at least 2 values after splitting.
String session = possibleSessionCookie.split("=")[1]
// store `session` somewhere
return
}
}
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)