io.netty.handler.codec.http.cookie.ServerCookieEncoder Java Examples
The following examples show how to use
io.netty.handler.codec.http.cookie.ServerCookieEncoder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpController.java From litchi with Apache License 2.0 | 6 votes |
public void writeFile(String fileName, String text) { ByteBuf content = Unpooled.copiedBuffer(text, CharsetUtil.UTF_8); HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); response.headers().set("Pragma", "Pragma"); response.headers().set("Expires", "0"); response.headers().set("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.headers().set("Content-Type", "application/download"); response.headers().set("Content-Disposition", "attachment;filename=" + fileName); response.headers().set("Content-Transfer-Encoding", "binary"); if (enableCookies) { for (Map.Entry<String, Cookie> entry : cookieMaps.entrySet()) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(entry.getValue())); } } // 跨域支持 response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "POST"); HttpUtil.setContentLength(response, content.readableBytes()); channel.writeAndFlush(response); //.addListener(ChannelFutureListener.CLOSE); }
Example #2
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 6 votes |
static void addStreamHandlers(Channel ch, ChannelOperations.OnSetup opsFactory, ConnectionObserver listener, boolean readForwardHeaders, ServerCookieEncoder encoder, ServerCookieDecoder decoder) { if (ACCESS_LOG) { ch.pipeline() .addLast(NettyPipeline.AccessLogHandler, new AccessLogHandlerH2()); } ch.pipeline() .addLast(NettyPipeline.H2ToHttp11Codec, new Http2StreamFrameToHttpObjectCodec(true)) .addLast(NettyPipeline.HttpTrafficHandler, new Http2StreamBridgeServerHandler(listener, readForwardHeaders, encoder, decoder)); ChannelOperations.addReactiveBridge(ch, opsFactory, listener); if (log.isDebugEnabled()) { log.debug(format(ch, "Initialized HTTP/2 stream pipeline {}"), ch.pipeline()); } }
Example #3
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 6 votes |
static void configureH2Pipeline(ChannelPipeline p, ServerCookieDecoder cookieDecoder, ServerCookieEncoder cookieEncoder, boolean forwarded, Http2Settings http2Settings, ConnectionObserver listener, ChannelOperations.OnSetup opsFactory, boolean validate) { p.remove(NettyPipeline.ReactiveBridge); Http2FrameCodecBuilder http2FrameCodecBuilder = Http2FrameCodecBuilder.forServer() .validateHeaders(validate) .initialSettings(http2Settings); if (p.get(NettyPipeline.LoggingHandler) != null) { http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "reactor.netty.http.server.h2")); } p.addLast(NettyPipeline.HttpCodec, http2FrameCodecBuilder.build()) .addLast(NettyPipeline.H2MultiplexHandler, new Http2MultiplexHandler(new H2Codec(opsFactory, listener, forwarded, cookieEncoder, cookieDecoder))); }
Example #4
Source File: WebSocketHelper.java From whirlpool with Apache License 2.0 | 6 votes |
public static void realWriteAndFlush(Channel channel, String text, String contentType, boolean keepalive, DefaultCookie nettyCookie) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(text + "\r\n", CharsetUtil.UTF_8)); HttpUtil.setContentLength(response, text.length()); response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType); setDateAndCacheHeaders(response, null); if (keepalive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } if (nettyCookie != null) { response.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(nettyCookie)); } // Write the initial line and the header. channel.write(response); channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); }
Example #5
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 6 votes |
Http11OrH2CleartextCodec( ServerCookieDecoder cookieDecoder, ServerCookieEncoder cookieEncoder, boolean debug, boolean forwarded, Http2Settings http2Settings, ConnectionObserver listener, ChannelOperations.OnSetup opsFactory, boolean validate) { this.cookieDecoder = cookieDecoder; this.cookieEncoder = cookieEncoder; this.forwarded = forwarded; Http2FrameCodecBuilder http2FrameCodecBuilder = Http2FrameCodecBuilder.forServer() .validateHeaders(validate) .initialSettings(http2Settings); if (debug) { http2FrameCodecBuilder.frameLogger(new Http2FrameLogger( LogLevel.DEBUG, "reactor.netty.http.server.h2")); } this.http2FrameCodec = http2FrameCodecBuilder.build(); this.listener = listener; this.opsFactory = opsFactory; }
Example #6
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 6 votes |
H2OrHttp11Codec( @Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate, ServerCookieDecoder cookieDecoder, ServerCookieEncoder cookieEncoder, HttpRequestDecoderSpec decoder, boolean forwarded, Http2Settings http2Settings, ConnectionObserver listener, @Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder, int minCompressionSize, ChannelOperations.OnSetup opsFactory, @Nullable Function<String, String> uriTagValue) { super(ApplicationProtocolNames.HTTP_1_1); this.compressPredicate = compressPredicate; this.cookieDecoder = cookieDecoder; this.cookieEncoder = cookieEncoder; this.decoder = decoder; this.forwarded = forwarded; this.http2Settings = http2Settings; this.listener = listener; this.metricsRecorder = metricsRecorder; this.minCompressionSize = minCompressionSize; this.opsFactory = opsFactory; this.uriTagValue = uriTagValue; }
Example #7
Source File: HttpServerOperations.java From reactor-netty with Apache License 2.0 | 6 votes |
HttpServerOperations(Connection c, ConnectionObserver listener, @Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate, HttpRequest nettyRequest, @Nullable ConnectionInfo connectionInfo, ServerCookieEncoder encoder, ServerCookieDecoder decoder) { super(c, listener); this.nettyRequest = nettyRequest; this.path = resolvePath(nettyRequest.uri()); this.nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); this.responseHeaders = nettyResponse.headers(); this.responseHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); this.compressionPredicate = compressionPredicate; this.cookieHolder = Cookies.newServerRequestHolder(requestHeaders(), decoder); this.connectionInfo = connectionInfo; this.cookieEncoder = encoder; this.cookieDecoder = decoder; }
Example #8
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 6 votes |
@SuppressWarnings("FutureReturnValueIgnored") private void doTestStatus(HttpResponseStatus status) { EmbeddedChannel channel = new EmbeddedChannel(); HttpServerOperations ops = new HttpServerOperations( Connection.from(channel), ConnectionObserver.emptyListener(), null, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"), null, ServerCookieEncoder.STRICT, ServerCookieDecoder.STRICT); ops.status(status); HttpMessage response = ops.newFullBodyMessage(Unpooled.EMPTY_BUFFER); assertThat(((FullHttpResponse) response).status().reasonPhrase()).isEqualTo(status.reasonPhrase()); // "FutureReturnValueIgnored" is suppressed deliberately channel.close(); }
Example #9
Source File: HttpSessionManager.java From glowroot with Apache License 2.0 | 6 votes |
private CommonResponse createSession(String username, Set<String> roles, boolean ldap) throws Exception { String sessionId = new BigInteger(130, secureRandom).toString(32); ImmutableSession session = ImmutableSession.builder() .caseAmbiguousUsername(username) .ldap(ldap) .roles(roles) .lastRequest(clock.currentTimeMillis()) .build(); sessionMap.put(sessionId, session); String layoutJson = layoutService .getLayoutJson(session.createAuthentication(central, configRepository)); CommonResponse response = new CommonResponse(OK, MediaType.JSON_UTF_8, layoutJson); Cookie cookie = new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), sessionId); cookie.setHttpOnly(true); cookie.setPath("/"); response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); purgeExpiredSessions(); auditSuccessfulLogin(username); return response; }
Example #10
Source File: SessionAwareWebClientTest.java From vertx-web with Apache License 2.0 | 6 votes |
@Test public void testReadManyCookies(TestContext context) { Async async = context.async(); prepareServer(context, req -> { req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test1", "toast1"))); req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test2", "toast2"))); req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test3", "toast3"))); }); client.get(PORT, "localhost", "/").send(ar -> { context.assertTrue(ar.succeeded()); validate(context, client.cookieStore().get(false, "localhost", "/"), new String[] { "test1" ,"test2", "test3" }, new String[] { "toast1", "toast2", "toast3" }); async.complete(); }); }
Example #11
Source File: WebRunHandler.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception { Client client = factory.get(ctx.channel()); RequestInfo info = parseUrl(req, PATH); if(StringUtils.isEmpty(info.getToken())) { throw new HttpException(HttpResponseStatus.BAD_REQUEST, "Missing token"); } try { AppHandoffToken authenticationToken = new AppHandoffToken(info.getToken()); authenticationToken.setHost(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString()); authenticationToken.setRememberMe(true); client.login(authenticationToken); FullHttpResponse response = redirect(info.toQueryString(webUrl).toString()); DefaultCookie cookie = authenticator.createCookie(client.getSessionId()); response.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); return response; } catch(AuthenticationException e) { logger.debug("Failed to authenticate token, redirecting to web anyway"); return redirect(info.toQueryString(webUrl).toString()); } }
Example #12
Source File: HttpController.java From litchi with Apache License 2.0 | 6 votes |
public void write(String text, String contentType) { ByteBuf content = Unpooled.copiedBuffer(text, CharsetUtil.UTF_8); HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); response.headers().set(CONTENT_TYPE, contentType); if (enableCookies) { for (Map.Entry<String, Cookie> entry : cookieMaps.entrySet()) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(entry.getValue())); } } // 跨域支持 response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "POST"); HttpUtil.setContentLength(response, content.readableBytes()); channel.writeAndFlush(response); //.addListener(ChannelFutureListener.CLOSE); }
Example #13
Source File: AdminAuthHandler.java From blynk-server with GNU General Public License v3.0 | 5 votes |
@POST @Path("/logout") public Response logout() { Response response = redirect(rootPath); Cookie cookie = makeDefaultSessionCookie("", 0); response.headers().add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); return response; }
Example #14
Source File: AdminAuthHandler.java From blynk-server with GNU General Public License v3.0 | 5 votes |
@POST @Consumes(value = MediaType.APPLICATION_FORM_URLENCODED) @Path("/login") public Response login(@FormParam("email") String email, @FormParam("password") String password) { if (email == null || password == null) { return redirect(rootPath); } User user = userDao.getByName(email, AppNameUtil.BLYNK); if (user == null || !user.isSuperAdmin) { return redirect(rootPath); } if (!password.equals(user.pass)) { return redirect(rootPath); } Response response = redirect(rootPath); log.debug("Admin login is successful. Redirecting to {}", rootPath); Cookie cookie = makeDefaultSessionCookie(sessionDao.generateNewSession(user), COOKIE_EXPIRE_TIME); response.headers().add(SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); return response; }
Example #15
Source File: TestUtils.java From nomulus with Apache License 2.0 | 5 votes |
public static FullHttpResponse makeEppHttpResponse( String content, HttpResponseStatus status, Cookie... cookies) { FullHttpResponse response = makeHttpResponse(content, status); response.headers().set("content-type", "application/epp+xml"); for (Cookie cookie : cookies) { response.headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(cookie)); } return response; }
Example #16
Source File: HttpSessionManager.java From glowroot with Apache License 2.0 | 5 votes |
void deleteSessionCookie(CommonResponse response) throws Exception { Cookie cookie = new DefaultCookie(configRepository.getWebConfig().sessionCookieName(), ""); cookie.setHttpOnly(true); cookie.setMaxAge(0); cookie.setPath("/"); response.setHeader(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); }
Example #17
Source File: HttpTrafficHandler.java From reactor-netty with Apache License 2.0 | 5 votes |
HttpTrafficHandler(ConnectionObserver listener, boolean readForwardHeaders, @Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compress, ServerCookieEncoder encoder, ServerCookieDecoder decoder) { this.listener = listener; this.readForwardHeaders = readForwardHeaders; this.compress = compress; this.cookieEncoder = encoder; this.cookieDecoder = decoder; }
Example #18
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 5 votes |
HttpServerChannelInitializer( @Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate, ServerCookieDecoder cookieDecoder, ServerCookieEncoder cookieEncoder, HttpRequestDecoderSpec decoder, boolean forwarded, Http2Settings http2Settings, @Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder, int minCompressionSize, ChannelOperations.OnSetup opsFactory, int protocols, ProxyProtocolSupportType proxyProtocolSupportType, @Nullable SslProvider sslProvider, @Nullable Function<String, String> uriTagValue) { this.compressPredicate = compressPredicate; this.cookieDecoder = cookieDecoder; this.cookieEncoder = cookieEncoder; this.decoder = decoder; this.forwarded = forwarded; this.http2Settings = http2Settings; this.metricsRecorder = metricsRecorder; this.minCompressionSize = minCompressionSize; this.opsFactory = opsFactory; this.protocols = protocols; this.proxyProtocolSupportType = proxyProtocolSupportType; this.sslProvider = sslProvider; this.uriTagValue = uriTagValue; }
Example #19
Source File: SessionAwareWebClientTest.java From vertx-web with Apache License 2.0 | 5 votes |
@Test public void testReadCookie(TestContext context) { Async async = context.async(); prepareServer(context, req -> { req.response().headers().add("set-cookie", ServerCookieEncoder.STRICT.encode(new DefaultCookie("test", "toast"))); }); client.get(PORT, "localhost", "/").send(ar -> { context.assertTrue(ar.succeeded()); validate(context, client.cookieStore().get(false, "localhost", "/"), new String[] { "test" }, new String[] { "toast" }); async.complete(); }); }
Example #20
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 5 votes |
H2Codec(ChannelOperations.OnSetup opsFactory, ConnectionObserver listener, boolean forwarded, ServerCookieEncoder encoder, ServerCookieDecoder decoder) { this.forwarded = forwarded; this.listener = listener; this.cookieEncoder = encoder; this.cookieDecoder = decoder; this.opsFactory = opsFactory; }
Example #21
Source File: BaseTransport.java From vertx-web with Apache License 2.0 | 5 votes |
static MultiMap removeCookieHeaders(MultiMap headers) { // We don't want to remove the JSESSION cookie. String cookieHeader = headers.get(COOKIE); if (cookieHeader != null) { headers.remove(COOKIE); Set<Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader); for (Cookie cookie: nettyCookies) { if (cookie.name().equals("JSESSIONID")) { headers.add(COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); break; } } } return headers; }
Example #22
Source File: HttpServerConfig.java From reactor-netty with Apache License 2.0 | 5 votes |
HttpServerConfig(Map<ChannelOption<?>, ?> options, Map<ChannelOption<?>, ?> childOptions, Supplier<? extends SocketAddress> localAddress) { super(options, childOptions, localAddress); this.cookieDecoder = ServerCookieDecoder.STRICT; this.cookieEncoder = ServerCookieEncoder.STRICT; this.decoder = new HttpRequestDecoderSpec(); this.forwarded = false; this.minCompressionSize = -1; this.protocols = new HttpProtocol[]{HttpProtocol.HTTP11}; this._protocols = h11; this.proxyProtocolSupportType = ProxyProtocolSupportType.OFF; }
Example #23
Source File: HttpResponseExecutor.java From redant with Apache License 2.0 | 5 votes |
private void buildHeaders(HttpResponse response, RedantContext redantContext) { if (response == null) { return; } FullHttpResponse fullHttpResponse = (FullHttpResponse) response; fullHttpResponse.headers().add(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(fullHttpResponse.content().readableBytes())); // 写cookie Set<Cookie> cookies = redantContext.getCookies(); if (CollectionUtil.isNotEmpty(cookies)) { for (Cookie cookie : cookies) { fullHttpResponse.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } }
Example #24
Source File: SessionLogoutResponder.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception { try { logger.debug("User requested logout"); factory.get(ctx.channel()).logout(); } catch (Throwable t) { logger.debug("Error attempting to logout current user", t); } finally { DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED); DefaultCookie nettyCookie = authenticator.expireCookie(); resp.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(nettyCookie)); httpSender.sendHttpResponse(ctx, req, resp); } }
Example #25
Source File: SessionAuth.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public boolean handleFailedAuth(ChannelHandlerContext ctx, FullHttpRequest req) { logger.debug("Handling failed auth for request: {}", req); DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED); DefaultCookie nettyCookie = authenticator.expireCookie(); resp.headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(nettyCookie)); httpSender.sendHttpResponse(ctx, req, resp); return true; }
Example #26
Source File: ShiroAuthenticator.java From arcusplatform with Apache License 2.0 | 5 votes |
private FullHttpResponse createErrorResponse(DefaultCookie cookie) { DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED); if (cookie != null) { resp.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } resp.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); return resp; }
Example #27
Source File: HttpSnoopServerHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.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(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().setInt(HttpHeaderNames.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(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Encode the cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie: cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
Example #28
Source File: HttpExecutor.java From bitchat with Apache License 2.0 | 5 votes |
private void buildHeaders(HttpResponse response, HttpContext httpContext) { if (response == null) { return; } FullHttpResponse fullHttpResponse = (FullHttpResponse) response; fullHttpResponse.headers().add(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(fullHttpResponse.content().readableBytes())); // 写cookie Set<Cookie> cookies = httpContext.getCookies(); if (CollectionUtil.isNotEmpty(cookies)) { for (Cookie cookie : cookies) { fullHttpResponse.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } }
Example #29
Source File: HttpSnoopServerHandler.java From julongchain with Apache License 2.0 | 5 votes |
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // 用以判断是否要关闭链接. boolean keepAlive = HttpUtil.isKeepAlive(request); // 构建Respons对象. FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, currentObj.decoderResult().isSuccess()? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // 只为keep-alive 链接增加 'Content-Length' 头. response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 根据以下规范增加 keep alive header a头: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // 编码 cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // 重置cookie. for (Cookie cookie: cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // 为浏览器添加一些cookie. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // 发送响应内容. ctx.write(response); return keepAlive; }
Example #30
Source File: HttpSnoopServerHandler.java From tools-journey with Apache License 2.0 | 5 votes |
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.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(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().setInt(HttpHeaderNames.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(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Encode the cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie: cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }