Example usage for io.netty.handler.codec.http HttpUtil isTransferEncodingChunked

List of usage examples for io.netty.handler.codec.http HttpUtil isTransferEncodingChunked

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpUtil isTransferEncodingChunked.

Prototype

public static boolean isTransferEncodingChunked(HttpMessage message) 

Source Link

Document

Checks to see if the transfer encoding in a specified HttpMessage is chunked

Usage

From source file:ccwihr.client.t1.HttpUploadClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.status());
        System.err.println("VERSION: " + response.protocolVersion());

        if (!response.headers().isEmpty()) {
            for (CharSequence name : response.headers().names()) {
                for (CharSequence value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }//from w  w  w .  java  2  s .  c  o m
            }
        }

        if (response.status().code() == 200 && HttpUtil.isTransferEncodingChunked(response)) {
            readingChunks = true;
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        System.err.println(chunk.content().toString(CharsetUtil.UTF_8));

        if (chunk instanceof LastHttpContent) {
            if (readingChunks) {
                System.err.println("} END OF CHUNKED CONTENT");
            } else {
                System.err.println("} END OF CONTENT");
            }
            readingChunks = false;
        } else {
            System.err.println(chunk.content().toString(CharsetUtil.UTF_8));
        }
    }
}

From source file:com.cmz.http.snoop.HttpSnoopClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.status());
        System.err.println("VERSION: " + response.protocolVersion());
        System.err.println();//from  w  ww  .  j  a  v a  2s  .  c om

        if (!response.headers().isEmpty()) {
            for (CharSequence name : response.headers().names()) {
                for (CharSequence value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }
            }
            System.err.println();
        }

        if (HttpUtil.isTransferEncodingChunked(response)) {
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.err.print(content.content().toString(CharsetUtil.UTF_8));
        System.err.flush();

        if (content instanceof LastHttpContent) {
            System.err.println("} END OF CONTENT");
            ctx.close();
        }
    }
}

From source file:com.cmz.http.upload.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//w w  w  .  j a  v  a2 s.co  m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpUtil.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:com.flysoloing.learning.network.netty.spdy.client.HttpResponseClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.out.println("STATUS: " + response.status());
        System.out.println("VERSION: " + response.protocolVersion());
        System.out.println();// w  w w  . j a v a2 s  .c  o  m

        if (!response.headers().isEmpty()) {
            for (CharSequence name : response.headers().names()) {
                for (CharSequence value : response.headers().getAll(name)) {
                    System.out.println("HEADER: " + name + " = " + value);
                }
            }
            System.out.println();
        }

        if (HttpUtil.isTransferEncodingChunked(response)) {
            System.out.println("CHUNKED CONTENT {");
        } else {
            System.out.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.out.print(content.content().toString(CharsetUtil.UTF_8));
        System.out.flush();

        if (content instanceof LastHttpContent) {
            System.out.println("} END OF CONTENT");
            queue.add(ctx.channel().newSucceededFuture());
        }
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (!msg.decoderResult().isSuccess()) {
        failAndClose(new IOException("Failed to parse the HTTP response."), ctx);
        return;/*  www. j  av a 2  s .c om*/
    }
    if (!(msg instanceof HttpResponse) && !(msg instanceof HttpContent)) {
        failAndClose(
                new IllegalArgumentException("Unsupported message type: " + StringUtil.simpleClassName(msg)),
                ctx);
        return;
    }
    checkState(userPromise != null, "response before request");

    if (msg instanceof HttpResponse) {
        response = (HttpResponse) msg;
        if (!response.protocolVersion().equals(HttpVersion.HTTP_1_1)) {
            HttpException error = new HttpException(response,
                    "HTTP version 1.1 is required, was: " + response.protocolVersion(), null);
            failAndClose(error, ctx);
            return;
        }
        if (!HttpUtil.isContentLengthSet(response) && !HttpUtil.isTransferEncodingChunked(response)) {
            HttpException error = new HttpException(response,
                    "Missing 'Content-Length' or 'Transfer-Encoding: chunked' header", null);
            failAndClose(error, ctx);
            return;
        }
        downloadSucceeded = response.status().equals(HttpResponseStatus.OK);
        if (!downloadSucceeded) {
            out = new ByteArrayOutputStream();
        }
        keepAlive = HttpUtil.isKeepAlive((HttpResponse) msg);
    }

    if (msg instanceof HttpContent) {
        checkState(response != null, "content before headers");

        ByteBuf content = ((HttpContent) msg).content();
        content.readBytes(out, content.readableBytes());
        if (msg instanceof LastHttpContent) {
            if (downloadSucceeded) {
                succeedAndReset(ctx);
            } else {
                String errorMsg = response.status() + "\n";
                errorMsg += new String(((ByteArrayOutputStream) out).toByteArray(),
                        HttpUtil.getCharset(response));
                out.close();
                HttpException error = new HttpException(response, errorMsg, null);
                failAndReset(error, ctx);
            }
        }
    }
}

From source file:com.linecorp.armeria.server.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//  w w w  .  j a  va 2 s. c om
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the method.
                if (!HttpMethod.isSupported(nettyReq.method().name())) {
                    fail(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
                    return;
                }

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                final boolean contentEmpty;
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }

                    contentEmpty = contentLength == 0;
                } else {
                    contentEmpty = true;
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController, cfg.defaultMaxRequestLength());

                // Close the request early when it is sure that there will be
                // neither content nor trailing headers.
                if (contentEmpty && !HttpUtil.isTransferEncodingChunked(nettyReq)) {
                    req.close();
                }

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                req.increaseTransferredBytes(dataLength);
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                if (req.isOpen()) {
                    req.write(new ByteBufHttpData(data.retain(), false));
                }
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (URISyntaxException e) {
        fail(ctx, HttpResponseStatus.BAD_REQUEST);
        if (req != null) {
            req.close(e);
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.linkedin.r2.transport.http.client.RAPResponseDecoder.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpResponse) {
        HttpResponse m = (HttpResponse) msg;
        _shouldCloseConnection = !HttpUtil.isKeepAlive(m);

        if (HttpUtil.is100ContinueExpected(m)) {
            ctx.writeAndFlush(CONTINUE).addListener(new ChannelFutureListener() {
                @Override//w  w  w.  j a  v  a2s .  co m
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }
        if (!m.decoderResult().isSuccess()) {
            ctx.fireExceptionCaught(m.decoderResult().cause());
            return;
        }
        // remove chunked encoding.
        if (HttpUtil.isTransferEncodingChunked(m)) {
            HttpUtil.setTransferEncodingChunked(m, false);
        }

        Timeout<None> timeout = ctx.channel().attr(TIMEOUT_ATTR_KEY).getAndRemove();
        if (timeout == null) {
            LOG.debug("dropped a response after channel inactive or exception had happened.");
            return;
        }

        final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, _maxContentLength,
                BUFFER_HIGH_WATER_MARK, BUFFER_LOW_WATER_MARK, timeout);
        EntityStream entityStream = EntityStreams.newEntityStream(writer);
        _chunkedMessageWriter = writer;
        StreamResponseBuilder builder = new StreamResponseBuilder();
        builder.setStatus(m.status().code());

        for (Map.Entry<String, String> e : m.headers()) {
            String key = e.getKey();
            String value = e.getValue();
            if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
                builder.addCookie(value);
            } else {
                builder.unsafeAddHeaderValue(key, value);
            }
        }

        ctx.fireChannelRead(builder.build(entityStream));
    } else if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        TimeoutBufferedWriter currentWriter = _chunkedMessageWriter;
        // Sanity check
        if (currentWriter == null) {
            throw new IllegalStateException("received " + HttpContent.class.getSimpleName() + " without "
                    + HttpResponse.class.getSimpleName());
        }

        if (!chunk.decoderResult().isSuccess()) {
            this.exceptionCaught(ctx, chunk.decoderResult().cause());
        }

        currentWriter.processHttpChunk(chunk);

        if (chunk instanceof LastHttpContent) {
            _chunkedMessageWriter = null;
            if (_shouldCloseConnection) {
                ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_DESTROY_SIGNAL);
            } else {
                ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_RELEASE_SIGNAL);
            }
        }
    } else {
        // something must be wrong, but let's proceed so that
        // handler after us has a chance to process it.
        ctx.fireChannelRead(msg);
    }
}

From source file:com.look.netty.demo.upload.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//from  w  ww.j  ava 2  s .c  o  m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpUtil.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            System.err.println(new String(responseContent.toString().getBytes(), "UTF-8"));
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:com.netty.file.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());

        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//from  www .ja  v a  2  s .c o m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        System.out.println("Helllllllllllllllllloooooooooooooo");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpUtil.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:com.shiyq.netty.http.HttpUploadServerHandler1.java

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/upload")) {
            // Write Menu
            //writeMenu(ctx);
            responseContent.append("{code:-1,message:''}");
            writeResponse(ctx.channel());
            return;
        }//  w ww  .  j a va  2 s  .  c  om
        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(HttpHeaderNames.COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = ServerCookieDecoder.STRICT.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                map.put(attr.getKey(), attrVal);
            }
        }

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("{code:-2,message:'??get'}");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append("{code:-3,message:'" + e1.getMessage() + "'}");
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpUtil.isTransferEncodingChunked(request);
        if (readingChunks) {
            // Chunk version
            //responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append("{code:-4,message:'" + e1.getMessage() + "'}");
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            //responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}