Example usage for io.netty.handler.codec.http HttpHeaders set

List of usage examples for io.netty.handler.codec.http HttpHeaders set

Introduction

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

Prototype

public HttpHeaders set(CharSequence name, Iterable<?> values) 

Source Link

Document

Sets a header with the specified name and values.

Usage

From source file: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)./*from   w w  w .j av  a  2 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 {
    // Start the connection attempt.
    // 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;
    try {
        uriGet = new URI(encoder.toString());
    } catch (URISyntaxException e) {
        logger.log(Level.WARNING, "Error: ", e);
        return null;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaders.Names.HOST, host);
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE);

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

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

    // send request
    List<Entry<String, String>> entries = headers.entries();
    channel.write(request).sync();

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

    return entries;
}

From source file:cc.changic.platform.etl.schedule.http.HttpHeaderUtil.java

License:Apache License

/**
 * Sets the value of the {@code "Connection"} header depending on the
 * protocol version of the specified message.  This getMethod sets or removes
 * the {@code "Connection"} header depending on what the default keep alive
 * mode of the message's protocol version is, as specified by
 * {@link io.netty.handler.codec.http.HttpVersion#isKeepAliveDefault()}.
 * <ul>//w  w  w .j  av  a  2  s .c  o m
 * <li>If the connection is kept alive by default:
 *     <ul>
 *     <li>set to {@code "close"} if {@code keepAlive} is {@code false}.</li>
 *     <li>remove otherwise.</li>
 *     </ul></li>
 * <li>If the connection is closed by default:
 *     <ul>
 *     <li>set to {@code "keep-alive"} if {@code keepAlive} is {@code true}.</li>
 *     <li>remove otherwise.</li>
 *     </ul></li>
 * </ul>
 */
public static void setKeepAlive(HttpMessage message, boolean keepAlive) {
    HttpHeaders h = message.headers();
    if (message.protocolVersion().isKeepAliveDefault()) {
        if (keepAlive) {
            h.remove(Names.CONNECTION);
        } else {
            h.set(Names.CONNECTION, Values.CLOSE);
        }
    } else {
        if (keepAlive) {
            h.set(Names.CONNECTION, Values.KEEP_ALIVE);
        } else {
            h.remove(Names.CONNECTION);
        }
    }
}

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   w w w .  j av  a 2 s . c  o 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: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)./*from w  w  w . j a v a2s  .c o  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();
}

From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

private static final FullHttpResponse http_200(String result) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(result.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}

From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

private static final FullHttpResponse http_404() {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}

From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

private static final FullHttpResponse http_500(String errorMessage) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(errorMessage.getBytes()));
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}

From source file:com.chiorichan.http.HttpResponseWrapper.java

License:Mozilla Public License

public void sendMultipart(byte[] bytesToWrite) throws IOException {
    if (request.method() == HttpMethod.HEAD)
        throw new IllegalStateException("You can't start MULTIPART mode on a HEAD Request.");

    if (stage != HttpResponseStage.MULTIPART) {
        stage = HttpResponseStage.MULTIPART;
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        HttpHeaders h = response.headers();
        try {/*from  w  w  w  .j  a v  a2  s  .c  o m*/
            request.getSession().save();
        } catch (SessionException e) {
            e.printStackTrace();
        }

        for (HttpCookie c : request.getCookies())
            if (c.needsUpdating())
                h.add("Set-Cookie", c.toHeaderValue());

        if (h.get("Server") == null)
            h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion());

        h.add("Access-Control-Allow-Origin",
                request.getLocation().getConfig().getString("site.web-allowed-origin", "*"));
        h.add("Connection", "close");
        h.add("Cache-Control", "no-cache");
        h.add("Cache-Control", "private");
        h.add("Pragma", "no-cache");
        h.set("Content-Type", "multipart/x-mixed-replace; boundary=--cwsframe");

        // if ( isKeepAlive( request ) )
        {
            // response.headers().set( CONNECTION, HttpHeaders.Values.KEEP_ALIVE );
        }

        request.getChannel().write(response);
    } else {
        StringBuilder sb = new StringBuilder();

        sb.append("--cwsframe\r\n");
        sb.append("Content-Type: " + httpContentType + "\r\n");
        sb.append("Content-Length: " + bytesToWrite.length + "\r\n\r\n");

        ByteArrayOutputStream ba = new ByteArrayOutputStream();

        ba.write(sb.toString().getBytes(encoding));
        ba.write(bytesToWrite);
        ba.flush();

        ChannelFuture sendFuture = request.getChannel().write(
                new ChunkedStream(new ByteArrayInputStream(ba.toByteArray())),
                request.getChannel().newProgressivePromise());

        ba.close();

        sendFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                NetworkManager.getLogger().info("Transfer complete.");
            }

            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
                if (total < 0)
                    NetworkManager.getLogger().info("Transfer progress: " + progress);
                else
                    NetworkManager.getLogger().info("Transfer progress: " + progress + " / " + total);
            }
        });
    }
}

From source file:com.chiorichan.http.HttpResponseWrapper.java

License:Mozilla Public License

/**
 * Sends the data to the client. Internal Use.
 *
 * @throws IOException/*from w  ww.j  av a  2 s. c om*/
 *              if there was a problem sending the data, like the connection was unexpectedly closed.
 */
public void sendResponse() throws IOException {
    if (stage == HttpResponseStage.CLOSED || stage == HttpResponseStage.WRITTEN)
        return;

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus, output);
    HttpHeaders h = response.headers();

    if (request.hasSession()) {
        Session session = request.getSession();

        /**
         * Initiate the Session Persistence Method.
         * This is usually done with a cookie but we should make a param optional
         */
        session.processSessionCookie(request.getDomain());

        for (HttpCookie c : session.getCookies().values())
            if (c.needsUpdating())
                h.add("Set-Cookie", c.toHeaderValue());

        if (session.getSessionCookie().needsUpdating())
            h.add("Set-Cookie", session.getSessionCookie().toHeaderValue());
    }

    if (h.get("Server") == null)
        h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion());

    // This might be a temporary measure - TODO Properly set the charset for each request.
    h.set("Content-Type", httpContentType + "; charset=" + encoding.name());

    h.add("Access-Control-Allow-Origin",
            request.getLocation().getConfig().getString("site.web-allowed-origin", "*"));

    for (Entry<String, String> header : headers.entrySet())
        h.add(header.getKey(), header.getValue());

    // Expires: Wed, 08 Apr 2015 02:32:24 GMT
    // DateTimeFormatter formatter = DateTimeFormat.forPattern( "EE, dd-MMM-yyyy HH:mm:ss zz" );

    // h.set( HttpHeaders.Names.EXPIRES, formatter.print( DateTime.now( DateTimeZone.UTC ).plusDays( 1 ) ) );
    // h.set( HttpHeaders.Names.CACHE_CONTROL, "public, max-age=86400" );

    h.setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    h.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    stage = HttpResponseStage.WRITTEN;

    request.getChannel().writeAndFlush(response);
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Tests blob POST, GET, HEAD and DELETE operations.
 * @throws ExecutionException//from w w w  .  j  a v a 2 s . c  om
 * @throws InterruptedException
 */
@Test
public void postGetHeadDeleteTest() throws ExecutionException, InterruptedException {
    ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(1024));
    String serviceId = "postGetHeadDeleteServiceID";
    String contentType = "application/octet-stream";
    String ownerId = "postGetHeadDeleteOwnerID";
    HttpHeaders headers = new DefaultHttpHeaders();
    setAmbryHeaders(headers, content.capacity(), 7200, false, serviceId, contentType, ownerId);
    headers.set(HttpHeaders.Names.CONTENT_LENGTH, content.capacity());
    headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key1", "value1");
    headers.add(RestUtils.Headers.USER_META_DATA_HEADER_PREFIX + "key2", "value2");

    String blobId = postBlobAndVerify(headers, content);
    getBlobAndVerify(blobId, headers, content);
    getHeadAndVerify(blobId, headers);
    deleteBlobAndVerify(blobId);

    // check GET, HEAD and DELETE after delete.
    verifyOperationsAfterDelete(blobId);
}