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

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

Introduction

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

Prototype

public abstract List<Map.Entry<String, String>> entries();

Source Link

Document

Returns a new List that contains all headers in this object.

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 ww  .j  a v  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: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  ava  2s . com
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)./*  w  w  w.  j av  a  2s  . c om*/
 *
 * @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.github.mike10004.seleniumhelp.TrafficMonitorFilter.java

License:Apache License

protected void captureHeaders(HttpHeaders headers, HarRequest harRequest) {
    for (Map.Entry<String, String> header : headers.entries()) {
        harRequest.getHeaders().add(new HarNameValuePair(header.getKey(), header.getValue()));
    }//  ww  w.ja  v  a  2  s  .  c o m
}

From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java

License:Apache License

protected void captureResponseHeaders(HttpResponse httpResponse, HarResponse harResponse) {
    HttpHeaders headers = httpResponse.headers();
    for (Map.Entry<String, String> header : headers.entries()) {
        harResponse.getHeaders().add(new HarNameValuePair(header.getKey(), header.getValue()));
    }// ww w.  j a v  a2s  .com
}

From source file:com.king.platform.net.http.netty.response.HttpClientResponseHandler.java

License:Apache License

public void handleResponse(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequestContext httpRequestContext = ctx.channel().attr(HttpRequestContext.HTTP_REQUEST_ATTRIBUTE_KEY)
            .get();/*ww w. j ava2  s .  co  m*/

    if (httpRequestContext == null) {
        logger.trace("httpRequestContext is null, msg was {}", msg);
        return;
    }

    NettyHttpClientResponse nettyHttpClientResponse = httpRequestContext.getNettyHttpClientResponse();

    RequestEventBus requestEventBus = nettyHttpClientResponse.getRequestEventBus();

    ResponseBodyConsumer responseBodyConsumer = nettyHttpClientResponse.getResponseBodyConsumer();

    try {

        if (msg instanceof HttpResponse) {
            requestEventBus.triggerEvent(Event.TOUCH);

            logger.trace("read HttpResponse");
            HttpResponse response = (HttpResponse) msg;

            HttpResponseStatus httpResponseStatus = response.getStatus();
            HttpHeaders httpHeaders = response.headers();

            nettyHttpClientResponse.setHttpResponseStatus(httpResponseStatus);
            nettyHttpClientResponse.setHttpHeaders(httpHeaders);

            requestEventBus.triggerEvent(Event.onReceivedStatus, httpResponseStatus);
            requestEventBus.triggerEvent(Event.onReceivedHeaders, httpHeaders);

            httpRequestContext.getTimeRecorder().readResponseHttpHeaders();

            if (httpRequestContext.isFollowRedirects()
                    && httpRedirector.isRedirectResponse(httpResponseStatus)) {
                httpRedirector.redirectRequest(httpRequestContext, httpHeaders);
                return;
            }

            if (response.getStatus().code() == 100) {
                requestEventBus.triggerEvent(Event.WRITE_BODY, ctx);
                return;
            }

            String contentLength = httpHeaders.get(HttpHeaders.Names.CONTENT_LENGTH);

            String contentType = httpHeaders.get(HttpHeaders.Names.CONTENT_TYPE);
            String charset = StringUtil.substringAfter(contentType, '=');
            if (charset == null) {
                charset = StandardCharsets.ISO_8859_1.name();
            }

            contentType = StringUtil.substringBefore(contentType, ';');

            if (contentLength != null) {
                long length = Long.parseLong(contentLength);
                responseBodyConsumer.onBodyStart(contentType, charset, length);
            } else {
                responseBodyConsumer.onBodyStart(contentType, charset, 0);
            }

            httpRequestContext.getTimeRecorder().responseBodyStart();

        } else if (msg instanceof HttpContent) {
            logger.trace("read HttpContent");
            requestEventBus.triggerEvent(Event.TOUCH);

            HttpResponseStatus httpResponseStatus = nettyHttpClientResponse.getHttpResponseStatus();
            HttpHeaders httpHeaders = nettyHttpClientResponse.getHttpHeaders();

            if (httpResponseStatus == null || (httpRequestContext.isFollowRedirects()
                    && httpRedirector.isRedirectResponse(httpResponseStatus))) {
                return;
            }

            if (msg == LastHttpContent.EMPTY_LAST_CONTENT
                    && nettyHttpClientResponse.getHttpResponseStatus().code() == 100) {
                logger.trace("read EMPTY_LAST_CONTENT with status code 100");
                return;
            }

            HttpContent chunk = (HttpContent) msg;

            ByteBuf content = chunk.content();

            content.resetReaderIndex();

            int readableBytes = content.readableBytes();

            if (readableBytes > 0) {
                ByteBuffer byteBuffer = content.nioBuffer();

                responseBodyConsumer.onReceivedContentPart(byteBuffer);
                requestEventBus.triggerEvent(Event.onReceivedContentPart, readableBytes, content);

            }

            content.release();

            requestEventBus.triggerEvent(Event.TOUCH);

            if (chunk instanceof LastHttpContent) {

                responseBodyConsumer.onCompletedBody();

                requestEventBus.triggerEvent(Event.onReceivedCompleted, httpResponseStatus, httpHeaders);
                httpRequestContext.getTimeRecorder().responseBodyCompleted();

                com.king.platform.net.http.HttpResponse httpResponse = new com.king.platform.net.http.HttpResponse(
                        httpResponseStatus.code(), responseBodyConsumer);

                for (Map.Entry<String, String> entry : httpHeaders.entries()) {
                    httpResponse.addHeader(entry.getKey(), entry.getValue());
                }

                requestEventBus.triggerEvent(Event.onHttpResponseDone, httpResponse);

                requestEventBus.triggerEvent(Event.COMPLETED, httpRequestContext);

            }
        }
    } catch (Throwable e) {
        requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, e);
    }
}

From source file:com.springapp.mvc.netty.example.http.upload.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 a2 s. 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(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");

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

    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.writeAndFlush(request);

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

    return entries;
}

From source file:com.titilink.camel.rest.common.AdapterRestletUtil.java

License:LGPL

/**
 * ?Restlet HttpRequest/*from  w  w w . j a va  2s  .com*/
 *
 * @param request nettyHttprequest
 * @return
 */
public static void parseToRestletHttpRequest(io.netty.handler.codec.http.HttpRequest request,
        HttpRequest restletRequest) {
    if (null == request || null == restletRequest) {
        LOGGER.error("invalid param, request or restletRequest is null");
        return;
    }
    //copy HttpRequest
    HttpHeaders headers = request.headers();
    for (Map.Entry<String, String> entry : headers.entries()) {
        HttpRequest.addHeader(restletRequest, entry.getKey(), entry.getValue());
    }
    //
    Method requestMethod = new Method(request.getMethod().name());
    restletRequest.setMethod(requestMethod);

    //??
    Protocol protocol = new Protocol(request.getProtocolVersion().protocolName());
    restletRequest.setProtocol(protocol);

    //Cookie
    Set<Cookie> cookies = null;
    @SuppressWarnings("rawtypes")
    Series<org.restlet.data.Cookie> restletCookies = (Series) Collections.emptySet();
    String value = request.headers().get(COOKIE);
    if (null == value) {
        cookies = Collections.emptySet();
    } else {
        cookies = CookieDecoder.decode(value);
    }
    for (Cookie cookie : cookies) {
        restletCookies.add(parseToRestletCookie(cookie));
    }
    restletRequest.setCookies(restletCookies);
}

From source file:com.titilink.camel.rest.common.AdapterRestletUtil.java

License:LGPL

public static void parseToNettyFullResponse(RestletServerCall httpCall,
        org.restlet.engine.adapter.HttpResponse response,
        io.netty.handler.codec.http.FullHttpResponse nettyResponse) {
    if (null == nettyResponse) {
        LOGGER.error("nettyResponse=null");
        return;/*  w  w  w .j  a  v  a 2  s  .c  o m*/
    }
    HttpHeaders nettyHeaders = nettyResponse.headers();

    if (null != response) {
        Series<Header> headers = response.getHeaders();
        if (null != headers) {
            for (Header parameter : headers) {
                if (null == parameter) {
                    continue;
                }
                String value = parameter.getValue();
                nettyHeaders.add(parameter.getName(), value);
            }
        }
    }
    nettyHeaders.set(DATE, new Date());

    // remove version information for security issue
    List<Map.Entry<String, String>> entries = nettyHeaders.entries();
    if (entries != null) {
        for (Map.Entry<String, String> entry : entries) {
            if (entry != null) {
                String value = entry.getValue();
                if (value != null && (Engine.VERSION_HEADER.equalsIgnoreCase(value)
                        || value.contains(Engine.VERSION_HEADER))) {
                    nettyHeaders.set(entry.getKey(), value.replaceAll(Engine.VERSION_HEADER, ""));
                }
            }
        }
    }
}

From source file:com.titilink.camel.rest.common.RestletServerCall.java

License:LGPL

@Override
public Series<Header> getRequestHeaders() {
    if (this.requestHeaders == null) {
        this.requestHeaders = new Series<Header>(Header.class);

        // Copy the headers from the request object
        String headerName;/* www  .j a  va  2  s .  c  o  m*/
        String headerValue;

        DefaultFullHttpRequest requestLocal = (DefaultFullHttpRequest) getRequest();

        HttpHeaders headers = requestLocal.headers();
        if (null != headers) {
            for (Map.Entry<String, String> entry : headers.entries()) {
                headerName = entry.getKey();
                headerValue = entry.getValue();
                this.requestHeaders.add(headerName, headerValue);
            }
        }
    }

    return this.requestHeaders;
}