Example usage for io.netty.handler.codec.http HttpRequest headers

List of usage examples for io.netty.handler.codec.http HttpRequest headers

Introduction

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

Prototype

HttpHeaders headers();

Source Link

Document

Returns the headers of this message.

Usage

From source file:HttpUploadServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//ww w .  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.getProtocolVersion().text() + "\r\n");

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

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : 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(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        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
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.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) {
                readHttpDataAllReceive(ctx.channel());
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *//*from  w  w  w  .  j  ava 2s. c om*/
private static List<InterfaceHttpData> formPost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {

    // Start the connection attempt
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false not multipart
    } catch (NullPointerException e) {
        // should not be since args are not null
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // test if getMethod is a POST getMethod
        e.printStackTrace();
    }

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    try {
        bodyRequestEncoder.addBodyAttribute("getform", "POST");
        bodyRequestEncoder.addBodyAttribute("info", "first value");
        bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
        bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
        bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
        bodyRequestEncoder.addBodyAttribute("Send", "Send");
    } catch (NullPointerException e) {
        // should not be since not null args
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // finalize request
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder).awaitUninterruptibly();
    }

    // Do not clear here since we will reuse the InterfaceHttpData on the
    // next request
    // for the example (limit action on client side). Take this as a
    // broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files
    // after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    return bodylist;
}

From source file:HttpUploadClient.java

License:Apache License

/**
 * Multipart example// w w  w.j  a  va 2 s  .  c  o m
 */
private static void formPostMultipart(Bootstrap bootstrap, String host, int port, URI uriFile,
        HttpDataFactory factory, List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist)
        throws Exception {

    // Start the connection attempt
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart
    } catch (NullPointerException e) {
        // should not be since no null args
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // test if getMethod is a POST getMethod
        e.printStackTrace();
    }

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    try {
        bodyRequestEncoder.setBodyHttpDatas(bodylist);
    } catch (NullPointerException e1) {
        // should not be since previously created
        e1.printStackTrace();
    } catch (ErrorDataEncoderException e1) {
        // again should not be since previously encoded (except if an error
        // occurs previously)
        e1.printStackTrace();
    }

    // finalize request
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder).awaitUninterruptibly();
    }

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}

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  ww  w.j ava  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:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {
        System.out.println(msg.toString());
    } else {// ww  w .j  av  a 2  s .c om
        System.out.println(ByteBufUtil.hexDump(((HttpContent) msg).content()));
        //System.out.println(((HttpContent) msg).content().toString(Charset.defaultCharset()));
    }

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

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

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

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : 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(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        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
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.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();
            }
        }
    }
}

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

License:Apache License

/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able
 * to achieve File upload due to limitation on request size).
 *
 * @return the list of headers that will be used in every example after
 **//*from   ww w.  j av a2 s.  co  m*/
private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get,
        URI uriSimple) throws Exception {
    // XXX /formget
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue &");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet = new URI(encoder.toString());
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaderNames.HOST, host);
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);

    headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
    headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    // connection will not close but needed
    // headers.set("Connection","keep-alive");
    // headers.set("Keep-Alive","300");

    headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"),
            new DefaultCookie("another-cookie", "bar")));

    // send request
    channel.writeAndFlush(request);

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    // convert headers to list
    return headers.entries();
}

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

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory
 * management)/*from   w  w  w.j  av  a  2 s. c om*/
 * @param se12 
 *
 * @return the list of HttpData object (attribute and file) to be reused on
 *         next post
 */
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        SyncEntity se12, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false

    // it is legal to add directly header or cookie into the request until
    // finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    // bodyRequestEncoder.addBodyFileUpload("myfile", file,
    // "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart
    // support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either
        // request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the
    // next request
    // for the example (limit action on client side). Take this as a
    // broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files
    // after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}

From source file:cf.service.NettyBrokerServer.java

License:Open Source License

private void validateAuthToken(HttpRequest request) throws RequestException {
    final String authToken = request.headers().get(VCAP_SERVICE_TOKEN_HEADER);
    if (!isValidAuthToken(authToken)) {
        throw new RequestException(HttpResponseStatus.UNAUTHORIZED);
    }/*from ww w.  jav a2  s .com*/
}

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);//from  ww w.  j  ava  2s .c om
        }

        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:cn.wcl.test.netty.HttpUploadClient.java

License:Apache License

/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload
 * due to limitation on request size)./*w  w  w  .ja v  a2 s . co  m*/
 *
 * @return the list of headers that will be used in every example after
 **/
private static List<Entry<String, String>> formget(Bootstrap bootstrap, String host, int port, String get,
        URI uriSimple) throws Exception {
    // XXX /formget
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue &");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet = new URI(encoder.toString());
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaderNames.HOST, host);
    headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);

    headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
    headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    //connection will not close but needed
    // headers.set("Connection","keep-alive");
    // headers.set("Keep-Alive","300");

    headers.set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"),
            new DefaultCookie("another-cookie", "bar")));

    // send request
    channel.writeAndFlush(request);

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    // convert headers to list
    return headers.entries();
}