当前位置: 首页>>代码示例>>Java>>正文


Java Cookie类代码示例

本文整理汇总了Java中io.netty.handler.codec.http.Cookie的典型用法代码示例。如果您正苦于以下问题:Java Cookie类的具体用法?Java Cookie怎么用?Java Cookie使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Cookie类属于io.netty.handler.codec.http包,在下文中一共展示了Cookie类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: toFullHttpResponse

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
/**
 * 转换为Netty所用Response
 * 
 * @return FullHttpResponse
 */
public FullHttpResponse toFullHttpResponse() {
	final FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpVersion, status, content);

	// headers
	final HttpHeaders httpHeaders = fullHttpResponse.headers().add(headers);
	httpHeaders.set(Names.CONTENT_TYPE, contentType + "; charset=" + charset);
	httpHeaders.set(Names.CONTENT_ENCODING, charset);
	httpHeaders.set(Names.CONTENT_LENGTH, content.readableBytes());

	// Cookies
	for (Cookie cookie : cookies) {
		httpHeaders.add(Names.SET_COOKIE, ServerCookieEncoder.encode(cookie));
	}

	return fullHttpResponse;
}
 
开发者ID:chenzehe,项目名称:ponycar,代码行数:22,代码来源:Response.java

示例2: getClientSessionId

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
public static String getClientSessionId(HttpRequest req) {
	Set<Cookie> cookies;
	String value = req.headers().get(HttpHeaders.Names.COOKIE);
	if (value == null) {
		return null;
	} else {
		cookies = CookieDecoder.decode(value);
	}

	for (Cookie cookie : cookies) {
		if (cookie.getName().contains("JSESSIONID")) {
			return cookie.getValue();
		}
	}

	return null;
}
 
开发者ID:osswangxining,项目名称:mqttserver,代码行数:18,代码来源:HttpSessionStore.java

示例3: channelRead0

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
	if (!request.getDecoderResult().isSuccess()) {
		sendError(ctx, BAD_REQUEST);
		return;
	}
				
	String uri = request.getUri();
	QueryStringDecoder decoder = new QueryStringDecoder(uri);			
	SimpleHttpRequest req = new SimpleHttpRequest(decoder.path(), decoder.parameters());
				
	String cookieString = request.headers().get(HttpHeaders.Names.COOKIE);
	if (cookieString != null) {
		Set<Cookie> cookies = CookieDecoder.decode(cookieString);
		req.setCookies(cookies);
	} else {
		req.setCookies(Collections.emptySet());
	}
	req.setHeaders(request.headers());
	copyHttpBodyData(request, req);
	
	SimpleHttpResponse resp =  eventHandler.apply(req);
	ctx.write( HttpEventHandler.buildHttpResponse(resp.toString(), resp.getStatus(), resp.getContentType()) );
	ctx.flush().close();
	
}
 
开发者ID:duchien85,项目名称:netty-cookbook,代码行数:27,代码来源:FunctionsChannelHandler.java

示例4: copyToServletCookie

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
void copyToServletCookie(FullHttpRequest fullHttpReq, MockHttpServletRequest servletRequest){
	String cookieString = fullHttpReq.headers().get(HttpHeaders.Names.COOKIE);
	if (cookieString != null) {
		Set<Cookie> cookies = CookieDecoder.decode(cookieString);
		if (!cookies.isEmpty()) {
	     // Reset the cookies if necessary.
			javax.servlet.http.Cookie[] sCookies = new javax.servlet.http.Cookie[cookies.size()];
			int i = 0;
			for (Cookie cookie: cookies) {
				javax.servlet.http.Cookie sCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
				sCookie.setPath(cookie.getPath());
				sCookie.setMaxAge((int) cookie.getMaxAge());
				sCookies[i++] = sCookie;
			}				
			servletRequest.setCookies(sCookies);
		}
       } else {
       	servletRequest.setCookies( new javax.servlet.http.Cookie[0]);
       }
}
 
开发者ID:duchien85,项目名称:netty-cookbook,代码行数:21,代码来源:ServletNettyChannelHandler.java

示例5: setSigned

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
public void setSigned(String name, String value, long timeout, String path, HttpServerRequest request) {
	Cookie cookie = new DefaultCookie(name, value);
	cookie.setMaxAge(timeout);
	cookie.setSecure("https".equals(Renders.getScheme(request)));
	cookie.setHttpOnly(true);
	if (path != null && !path.trim().isEmpty()) {
		cookie.setPath(path);
	}
	if (signKey != null) {
		try {
			signCookie(cookie);
		} catch (InvalidKeyException | NoSuchAlgorithmException
				| IllegalStateException | UnsupportedEncodingException e) {
			log.error(e);
			return;
		}
		request.response().headers().add("Set-Cookie", ServerCookieEncoder.encode(cookie));
	}
}
 
开发者ID:web-education,项目名称:web-utils,代码行数:20,代码来源:CookieHelper.java

示例6: _parseIfNeededAndGet

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
private synchronized Map<String, Set<Cookie>> _parseIfNeededAndGet() {
    if (cookiesParsed) { // This method is synchronized, so creates a memory barrier for this variable to be refreshed.
        return allCookies;
    }
    List<String> allCookieHeaders = nettyHeaders.getAll(cookiesHeaderName);
    Map<String, Set<Cookie>> cookies = new HashMap<String, Set<Cookie>>();
    for (String aCookieHeader : allCookieHeaders) {
        Set<Cookie> decode = CookieDecoder.decode(aCookieHeader);
        for (Cookie cookie : decode) {
            Set<Cookie> existingCookiesOfName = cookies.get(cookie.getName());
            if (null == existingCookiesOfName) {
                existingCookiesOfName = new HashSet<Cookie>();
                cookies.put(cookie.getName(), existingCookiesOfName);
            }
            existingCookiesOfName.add(cookie);
        }
    }
    allCookies = Collections.unmodifiableMap(cookies);
    cookiesParsed = true;
    return allCookies;
}
 
开发者ID:allenxwang,项目名称:RxNetty,代码行数:22,代码来源:CookiesHolder.java

示例7: testGetCookie

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
@Test
public void testGetCookie() throws Exception {
    DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    String cookie1Header = cookie1Name + '=' + cookie1Value
                           + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path=" + cookie1Path + "; domain=" + cookie1Domain;
    nettyResponse.headers().add(HttpHeaders.Names.SET_COOKIE, cookie1Header);
    HttpClientResponse<ByteBuf> response = new HttpClientResponse<ByteBuf>(nettyResponse, PublishSubject.<ByteBuf>create());
    Map<String,Set<Cookie>> cookies = response.getCookies();
    Assert.assertNotNull("Cookies are null.", cookies);
    Assert.assertEquals("Cookies are empty.", 1, cookies.size());
    Set<Cookie> cookies1 = cookies.get(cookie1Name);
    Assert.assertNotNull("No cookies found with name: " + cookie1Name, cookies1);
    Assert.assertEquals("Unexpected number of cookies found.", 1, cookies1.size());
    Cookie cookieFound = cookies1.iterator().next();
    Assert.assertEquals("unexpected cookie name.", cookie1Name, cookieFound.getName());
    Assert.assertEquals("unexpected cookie value.", cookie1Value, cookieFound.getValue());
    Assert.assertEquals("unexpected cookie path.", cookie1Path, cookieFound.getPath());
    Assert.assertEquals("unexpected cookie domain.", cookie1Domain, cookieFound.getDomain());
}
 
开发者ID:allenxwang,项目名称:RxNetty,代码行数:24,代码来源:CookieTest.java

示例8: testSetCookie

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
@Test
public void testSetCookie() throws Exception {
    DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    Cookie cookie = new DefaultCookie(cookie1Name, cookie1Value);
    cookie.setPath(cookie1Path);
    cookie.setDomain(cookie1Domain);
    new HttpClientRequest<ByteBuf>(nettyRequest).withCookie(cookie);
    String cookieHeader = nettyRequest.headers().get(HttpHeaders.Names.COOKIE);
    Assert.assertNotNull("No cookie header found.", cookieHeader);
    Set<Cookie> decodeCookies = CookieDecoder.decode(cookieHeader);
    Assert.assertNotNull("No cookie found with name.", decodeCookies);
    Assert.assertEquals("Unexpected number of cookies.", 1, decodeCookies.size());
    Cookie decodedCookie = decodeCookies.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookie1Name, decodedCookie.getName());
    Assert.assertEquals("Unexpected cookie path.", cookie1Path, decodedCookie.getPath());
    Assert.assertEquals("Unexpected cookie domain.", cookie1Domain, decodedCookie.getDomain());
}
 
开发者ID:allenxwang,项目名称:RxNetty,代码行数:22,代码来源:CookieTest.java

示例9: testGetCookie

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
@Test
public void testGetCookie() throws Exception {
    DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
    String cookie1Name = "PREF";
    String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi";
    String cookie1Domain = ".google.com";
    String cookie1Path = "/";
    String cookie1Header = cookie1Name + '=' + cookie1Value
                           + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path=" + cookie1Path + "; domain=" + cookie1Domain;
    nettyRequest.headers().add(HttpHeaders.Names.COOKIE, cookie1Header);
    HttpServerRequest<ByteBuf> request = new HttpServerRequest<ByteBuf>(nettyRequest, PublishSubject.<ByteBuf>create());
    Map<String,Set<Cookie>> cookies = request.getCookies();
    Assert.assertEquals("Unexpected number of cookies.", 1, cookies.size());
    Set<Cookie> cookies1 = cookies.get(cookie1Name);
    Assert.assertNotNull("No cookie found with name: " + cookie1Name, cookies1);
    Assert.assertEquals("Unexpected number of cookies with name: " + cookie1Name, 1, cookies1.size() );
    Cookie cookie = cookies1.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookie1Name, cookie.getName());
    Assert.assertEquals("Unexpected cookie path.", cookie1Path, cookie.getPath());
}
 
开发者ID:allenxwang,项目名称:RxNetty,代码行数:21,代码来源:CookieTest.java

示例10: testSetCookie

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
@Test
public void testSetCookie() throws Exception {
    DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    HttpServerResponse<ByteBuf> response = new HttpServerResponse<ByteBuf>(new NoOpChannelHandlerContext(),
                                                               nettyResponse);
    String cookieName = "name";
    String cookieValue = "value";
    response.addCookie(new DefaultCookie(cookieName, cookieValue));
    String cookieHeader = nettyResponse.headers().get(HttpHeaders.Names.SET_COOKIE);
    Assert.assertNotNull("Cookie header not found.", cookieHeader);
    Set<Cookie> decode = CookieDecoder.decode(cookieHeader);
    Assert.assertNotNull("Decoded cookie not found.", decode);
    Assert.assertEquals("Unexpected number of decoded cookie not found.", 1, decode.size());
    Cookie cookie = decode.iterator().next();
    Assert.assertEquals("Unexpected cookie name.", cookieName, cookie.getName());
    Assert.assertEquals("Unexpected cookie value.", cookieValue, cookie.getValue());

}
 
开发者ID:allenxwang,项目名称:RxNetty,代码行数:19,代码来源:CookieTest.java

示例11: setCookie

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
void setCookie(HttpRequest request, FullHttpResponse response) {
  // Encode the cookie.
  String cookieString = request.headers().get(COOKIE);
  if (cookieString != null) {
    Set<Cookie> cookies = CookieDecoder.decode(cookieString);
    if (!cookies.isEmpty()) {
      // Reset the cookies if necessary.
      for (Cookie cookie: cookies) {
        if("visit-count".equals(cookie.getName())) {
          int count = Integer.parseInt(cookie.getValue()) ;
          cookie.setValue(Integer.toString(count + 1));
          //System.out.println("Visit: " + count);
        }
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
      }
    }
  } else {
    // Browser sent no cookie.  Add some.
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("id", UUID.randomUUID().toString()));
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("visit-count", "1"));
    response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("first-visit-time", new Date().toString()));
  }
}
 
开发者ID:DemandCube,项目名称:Sparkngin,代码行数:24,代码来源:TrackingPixelRouteHandler.java

示例12: main

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
public static void main(String[] args) {
    Set<Cookie> cookies = new HashSet<>();
    cookies.add(new DefaultCookie("id", "123"));

    Optional<Cookie> cookie = cookies.stream().filter(c -> c.name().equalsIgnoreCase("id")).findFirst();

    if (cookie.isPresent())
        System.out.println(cookie.get());
    else
        System.out.println("none");
}
 
开发者ID:bruce-sha,项目名称:sardine,代码行数:12,代码来源:CookieTest.java

示例13: HttpRequestData

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
public HttpRequestData(HttpRequestEvent event){
	HttpHeaders headers = event.getRequest().headers();
	String refererUrl = NettyHttpUtil.getRefererUrl(headers);				
	String userAgent = headers.get(USER_AGENT);
	
	String cookieString = headers.get(COOKIE);
	Map<String, String> cookiesMap = null;
	if (cookieString != null) {			
		try {				
			Set<Cookie> cookies = CookieDecoder.decode(cookieString);			
			int z = cookies.size();
			if (z > 0) {
				cookiesMap = new HashMap<>(z);
				for (Cookie cookie : cookies) {
					cookiesMap.put(cookie.getName(), cookie.getValue());
				}										
			} else {
				cookiesMap = new HashMap<>(0);
			}
		} catch (Exception e) {			
			e.printStackTrace();
			System.err.println("--cookie: "+cookieString);
		}			
	}
	set(userAgent, refererUrl, event.getParams(), cookiesMap);		
	//System.out.println(cookieString + " request COOKIE " + cookies );
}
 
开发者ID:duchien85,项目名称:netty-cookbook,代码行数:28,代码来源:HttpRequestData.java

示例14: writeResponse

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, currentObj.getDecoderResult().isSuccess()? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie: cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
开发者ID:wuyinxian124,项目名称:netty4.0.27Learn,代码行数:40,代码来源:HttpSnoopServerHandler.java

示例15: writeResponse

import io.netty.handler.codec.http.Cookie; //导入依赖的package包/类
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, currentObj.decoderResult().isSuccess()? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Encode the cookie.
    String cookieString = request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            // Reset the cookies if necessary.
            for (Cookie cookie: cookies) {
                response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie));
            }
        }
    } else {
        // Browser sent no cookie.  Add some.
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
        response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
 
开发者ID:krisjey,项目名称:netty.book.kor,代码行数:40,代码来源:HttpSnoopServerHandler.java


注:本文中的io.netty.handler.codec.http.Cookie类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。