List of usage examples for io.netty.handler.codec.http HttpHeaders is100ContinueExpected
@Deprecated public static boolean is100ContinueExpected(HttpMessage message)
From source file:baseFrame.netty.atest.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w w w . j av a 2 s . c o m*/ boolean keepAlive = HttpHeaders.isKeepAlive(request); // Encode the cookie. String cookieString = request.headers().get(Names.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(Names.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } } else { // Browser sent no cookie. Add some. /* response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));*/ } if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } responseContent.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); //responseContent.append("HOSTNAME: ").append(request.headers().).append("\r\n"); responseContent.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Entry<String, String> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); responseContent.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } responseContent.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { responseContent.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } responseContent.append("\r\n"); } response = setResponse(response, responseContent); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; if (msg instanceof LastHttpContent) { } } }
From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/*from w w w.j a va 2s.com*/ } String uri = request.uri(); HttpMethod method = request.method(); Root root = Root.getInstance(); buf.setLength(0); contentBuf.setLength(0); if (method == HttpMethod.POST) { if (uri.equals("/chitchat")) { currentAction = "Add"; } } if (method == HttpMethod.GET) { if (uri.startsWith(LATEST)) { latestFromWho = decode(uri.substring(LATEST_SIZE)); currentAction = "Latest"; Message m = root.getLatest(latestFromWho); if (m != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(m.toJSON()); } } if (uri.startsWith(THREADCALL)) { currentAction = "Thread"; String threadId = uri.substring(THREADCALL_SIZE); MessageThread mt = root.getMessageThread(threadId); if (mt != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(mt.toJSON()); } } if (uri.startsWith(SEARCH)) { String stringToSearch = decode(uri.substring(SEARCH_SIZE)); currentAction = "search"; List<Message> lm = root.search(stringToSearch); //[{"author":"Loki", "text":"I have an army !", "thread":3, //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !", // "thread":3, "createdAt":1404736639715}] buf.append("["); if (!lm.isEmpty()) { Iterator<Message> it = lm.iterator(); Message m = it.next(); buf.append(m.toJSON()); while (it.hasNext()) { m = it.next(); buf.append(", "); buf.append(m.toJSON()); } } buf.append("]"); } } } if (msg instanceof HttpContent) { Root root = Root.getInstance(); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { contentBuf.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // buf.append("END OF CONTENT\r\n"); if (currentAction.equals("Add")) { addMessageFromContent(contentBuf.toString(), root); currentAction = "None"; } LastHttpContent trailer = (LastHttpContent) msg; if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:ch07.handlers.HttpSnoopServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/* w w w . j a v a 2 s.c o m*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.aerofs.baseline.http.HttpRequestHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (ctx.channel().closeFuture().isDone()) { LOGGER.warn("{}: drop http message - channel closed", Channels.getHexText(ctx)); return;/*from w w w . jav a2s .c o m*/ } if (!(msg instanceof HttpObject)) { super.channelRead(ctx, msg); } // // netty http decoding: // // 1. normal case: HttpRequest (headers), HttpContent (0+), LastHttpContent (trailing headers) // NOTE: with chunked transfer encoding or content-length non-zero you get an arbitrary number of HttpContent objects // 2. error case (failed to decode an HTTP message): HttpRequest with NETTY_HTTP_DECODING_FAILED_URI // if (msg instanceof HttpRequest) { // this is the first object netty generates: // an HttpRequest containing a number of headers // we should not have another request pending Preconditions.checkState(pendingRequest == null, "previous request pending:%s", pendingRequest); // cast it HttpRequest nettyRequest = (HttpRequest) msg; // get the request id String requestId = nettyRequest.headers().get(Headers.REQUEST_TRACING_HEADER); Preconditions.checkState(requestId != null, "http request on %s has no request id", Channels.getHexText(ctx)); // check if http decoding failed and if so, abort early if (nettyRequest.uri().equals(NETTY_HTTP_DECODING_FAILED_URI)) { LOGGER.warn("{}: [{}] fail http decoding", Channels.getHexText(ctx), requestId); ctx.read(); return; } // get a few headers we really care about HttpVersion httpVersion = nettyRequest.protocolVersion(); boolean keepAlive = HttpHeaders.isKeepAlive(nettyRequest); boolean transferEncodingChunked = HttpHeaders.isTransferEncodingChunked(nettyRequest); boolean continueExpected = HttpHeaders.is100ContinueExpected(nettyRequest); long contentLength = HttpHeaders.getContentLength(nettyRequest, ZERO_CONTENT_LENGTH); boolean hasContent = transferEncodingChunked || contentLength > ZERO_CONTENT_LENGTH; LOGGER.trace("{}: [{}] rq:{} ka:{} ck:{} ce:{} cl:{}", Channels.getHexText(ctx), requestId, nettyRequest, keepAlive, transferEncodingChunked, continueExpected, contentLength); // create the input stream used to read content ContentInputStream entityInputStream; if (hasContent) { entityInputStream = new EntityInputStream(httpVersion, continueExpected, ctx); } else { entityInputStream = EmptyEntityInputStream.EMPTY_ENTITY_INPUT_STREAM; } // create the object with which to write the response body PendingRequest pendingRequest = new PendingRequest(requestId, httpVersion, keepAlive, entityInputStream, ctx); // create the jersey request object final ContainerRequest jerseyRequest = new ContainerRequest(baseUri, URI.create(nettyRequest.uri()), nettyRequest.method().name(), DEFAULT_SECURITY_CONTEXT, PROPERTIES_DELEGATE); jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_CHANNEL_ID_PROPERTY, new ChannelId(Channels.getHexText(ctx))); jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_REQUEST_ID_PROPERTY, new RequestId(requestId)); jerseyRequest.header(Headers.REQUEST_TRACING_HEADER, requestId); // add request id to headers copyHeaders(nettyRequest.headers(), jerseyRequest); // copy headers from message jerseyRequest.setEntityStream(entityInputStream); jerseyRequest.setWriter(pendingRequest); // now we've got all the initial headers and are waiting for the entity this.pendingRequest = pendingRequest; // store the runnable that we want jersey to execute saveRequestRunnable(() -> { // all throwables caught by jersey internally - // handled by the ResponseWriter below // if, for some reason there's some weird error it'll be handled // by the default exception handler, which kills the process applicationHandler.handle(jerseyRequest); }); // IMPORTANT: // we pass this request up to be processed by // jersey before we've read any content. This allows // the resource to read from the InputStream // directly, OR, to use an @Consumes annotation with an // input objectType to invoke the appropriate parser // // since the request is consumed *before* the content // has been received readers may block. to prevent the // IO thread from blocking we have to execute all // request processing in an application threadpool if (hasContent) { submitPendingRunnable(); } // indicate that we want to keep reading // this is always the case when we receive headers // because we want to receive everything until // LastHttpContent ctx.read(); } else { // after receiving the http headers we get // a series of HttpContent objects that represent // the entity or a set of chunks // we should have received the headers already Preconditions.checkState(pendingRequest != null, "no pending request"); // we're not expecting anything other than content objects right now Preconditions.checkArgument(msg instanceof HttpContent, "HttpContent expected, not %s", msg.getClass().getSimpleName()); // handle the content HttpContent content = (HttpContent) msg; boolean last = msg instanceof LastHttpContent; LOGGER.trace("{}: [{}] handling content:{} last:{}", Channels.getHexText(ctx), pendingRequest.requestId, content.content().readableBytes(), last); pendingRequest.entityInputStream.addBuffer(content.content(), last); // transfers ownership to the HttpContentInputStream // FIXME (AG): support trailing headers // if it's the last piece of content, then we're done if (last) { // submit the request to jersey if we haven't yet if (savedRequestRunnable != null) { submitPendingRunnable(); } } } }
From source file:com.bala.learning.learning.netty.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// www . ja va 2s . c o m } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.digisky.innerproxy.server.InnerProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// w ww. j a v a 2 s. c om } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "content:" + content.toString(CharsetUtil.UTF_8)); String jsonmsg = null; try { jsonmsg = java.net.URLDecoder.decode(content.toString(CharsetUtil.UTF_8), "utf-8"); } catch (UnsupportedEncodingException e) { LogMgr.warn("", "URLDecoder exceptionn caught."); // e.printStackTrace(); } if (msgCheck(jsonmsg) == false) { //contain ';', bad. LogMgr.error(InnerProxyHttpServerHandler.class.getName(), "jsonmsg contain ; or ', close it. peer info:" + ctx.channel().remoteAddress().toString()); ctx.channel().close(); return; } LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "jsonmsg:" + jsonmsg); LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "method:" + request.getMethod()); String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); } else { //POST LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "type:" + type); // ugly code ProcessServerManager.getInstance().process(ctx.channel(), type, jsonmsg.replace("val=", "")); } } }
From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//ww w . j a v a 2 s .co m } } if (msg instanceof HttpContent) { String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); return; } else if (type.equals("email_pwd_reset") == true) { //? String[] tmp = request.getUri().split("="); String vcode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}"); return; } //email_active email_pwd_reset, //??? HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); InterfaceHttpData postData = decoder.getBodyHttpData("val"); if (postData instanceof FileUpload == false) {//outerProxy???? ctx.close(); return; } FileUpload binData = (FileUpload) postData; ByteBuf content = null; try { content = binData.getByteBuf(); } catch (IOException e) { e.printStackTrace(); } //content??. , 0. ?(head)?id, json?, ?. ??, ???. //?content?head int index = content.bytesBefore((byte) 0); if (index < 0) { LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request."); ctx.channel().close(); return; } byte[] head = new byte[index]; content.readBytes(head); String strHead = new String(head); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead); JSONObject jo = JSONObject.parseObject(strHead); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version")); content.readByte();//0 //?content?tail byte[] tail = new byte[content.readableBytes()]; content.readBytes(tail); String sjsonmsg = null; if (jo.getString("version").equals("0")) { //?0 byte[] bjsonmsg = XXTEA.decrypt(tail, key); int data_len = bjsonmsg.length; for (int i = bjsonmsg.length - 1; i != 0; --i) { if (bjsonmsg[i] == 0) { data_len--; continue; } else { break; } } try { sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { //TODO?0, app_id. ??? LogMgr.error(OuterProxyHttpServerHandler.class.getName(), "?0, ??"); ctx.close(); return; } sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//? LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg); //debug code //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model")); /* debug code //b.getBytes(n+1, tail, 0, b.g-n-1); for(int i=0; i< tail.length; ++i) { System.out.print(String.format("%x ", tail[i])); } */ //debug code //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg); // ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg); } }
From source file:com.github.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }// www. ja v a 2s . co m boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.mastfrog.acteur.server.UpstreamHandlerImpl.java
License:Open Source License
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest request = (HttpRequest) msg; if (!aggregateChunks && HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// w ww. j a va 2s . c om } SocketAddress addr = ctx.channel().remoteAddress(); if (decodeRealIP) { String hdr = request.headers().get("X-Real-IP"); if (hdr == null) { hdr = request.headers().get("X-Forwarded-For"); } if (hdr != null) { addr = new InetSocketAddress(hdr, addr instanceof InetSocketAddress ? ((InetSocketAddress) addr).getPort() : 80); } } EventImpl evt = new EventImpl(request, addr, ctx.channel(), paths, mapper); evt.setNeverKeepAlive(neverKeepAlive); application.onEvent(evt, ctx.channel()); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; SocketAddress addr = (SocketAddress) ctx.channel().remoteAddress(); // XXX - any way to decode real IP? WebSocketEvent wsEvent = new WebSocketEvent(frame, ctx.channel(), addr, mapper); application.onEvent(wsEvent, ctx.channel()); } else { if (uneh != null) { uneh.channelRead(ctx, msg); } } }
From source file:com.netty.BaseHttpServerHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; // HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//from w ww. jav a 2 s . co m boolean keepAlive = HttpHeaders.isKeepAlive(request); /////////////// FullHttpResponse response = handleRequest(request.getUri(), request.content().toString(CharsetUtil.UTF_8), request); //////////// // final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); // response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); // ctx.executor().submit(new Runnable() { // @Override // public void run() { ctx.write(response); // } // }); } } }