Example usage for io.netty.handler.codec.http HttpMethod GET

List of usage examples for io.netty.handler.codec.http HttpMethod GET

Introduction

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

Prototype

HttpMethod GET

To view the source code for io.netty.handler.codec.http HttpMethod GET.

Click Source Link

Document

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

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)./* ww w.ja  v  a  2  s  .com*/
 *
 * @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:adalightserver.http.HttpServer.java

License:Apache License

private void handleStaticFileRequest(ChannelHandlerContext ctx, FullHttpRequest req, String path)
        throws Exception {

    if (req.getMethod() != HttpMethod.GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;//from w  w w  .j av a2s .  c  o m
    }

    if (path.equals("/"))
        path = "/index.html";

    final String spath = sanitizeUri(path);
    if (spath == null) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }
    File file = new File(spath);
    if (file.isHidden() || !file.exists()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }
    if (file.isDirectory() || !file.isFile() || !file.canRead()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    RandomAccessFile raf = null;
    byte[] content;
    long fileLength;
    try {
        raf = new RandomAccessFile(file, "r");
        fileLength = raf.length();
        if (fileLength > 4 * 1024 * 1024) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
            return;
        }
        content = new byte[(int) fileLength];
        raf.read(content);
    } catch (Exception e) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;
    } finally {
        if (raf != null)
            raf.close();
    }

    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK);
    res.content().writeBytes(content);

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    res.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
    res.headers().set(HttpHeaders.Names.CONTENT_LENGTH, fileLength);

    sendHttpResponse(ctx, req, res);
}

From source file:br.unifei.edu.eco009.steamlansync.proxy.SteamActivityTracker.java

public void requestSentToServer(FullFlowContext flowContext, HttpRequest httpRequest) {
    if (httpRequest.getMethod().equals(HttpMethod.GET)
            && httpRequest.getUri().contains("steampowered.com/depot/")) {
        System.out.println(httpRequest.getUri());
        System.out.println(UriParser.getAppId(httpRequest));
    }//from  www .  j  a  va  2  s .co  m

}

From source file:br.unifei.edu.eco009.steamlansync.proxy.SteamDepotFilter.java

public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) {
    if (originalRequest.getMethod().equals(HttpMethod.GET)
            && originalRequest.getUri().contains("steampowered.com/depot/")
            && originalRequest.getUri().contains("chunk")) {

        // alterar o precedimento da
        // request:
        return new HttpFiltersAdapter(originalRequest) {
            boolean store = false;
            String chunkId = UriParser.getChunkId(originalRequest);
            HttpChunkContents cachedChunk;

            @Override/*from  ww w  .  j  a v a  2  s.com*/
            public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                //                        return chunks.get(getChunkId(originalRequest)).copy().retain();
                cachedChunk = SteamCache.getChunk(chunkId);
                if (cachedChunk == null) {
                    store = true;
                    System.out.println("cache MISS");
                    return super.clientToProxyRequest(httpObject);
                }
                System.out.println("cache HIT");
                return cachedChunk.getFullHttpResponse().retain();

            }

            @Override
            public HttpObject proxyToClientResponse(HttpObject httpObject) {
                FullHttpResponse resp = (FullHttpResponse) super.proxyToClientResponse(httpObject);
                //                        chunks.put(getChunkId(originalRequest), resp.copy());
                if (store) {
                    SteamCache.putChunk(chunkId, new HttpChunkContents(resp));
                }
                return resp;
            }

        };
    }
    return null;
}

From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//from   w w w. j  av a 2  s .  co m
        }
        String uri = request.uri();
        HttpMethod method = request.method();
        Root root = Root.getInstance();
        buf.setLength(0);
        contentBuf.setLength(0);

        if (method == HttpMethod.POST) {
            if (uri.equals("/chitchat")) {

                currentAction = "Add";
            }
        }
        if (method == HttpMethod.GET) {
            if (uri.startsWith(LATEST)) {
                latestFromWho = decode(uri.substring(LATEST_SIZE));
                currentAction = "Latest";
                Message m = root.getLatest(latestFromWho);
                if (m != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(m.toJSON());
                }
            }
            if (uri.startsWith(THREADCALL)) {
                currentAction = "Thread";
                String threadId = uri.substring(THREADCALL_SIZE);
                MessageThread mt = root.getMessageThread(threadId);
                if (mt != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(mt.toJSON());
                }

            }
            if (uri.startsWith(SEARCH)) {
                String stringToSearch = decode(uri.substring(SEARCH_SIZE));
                currentAction = "search";
                List<Message> lm = root.search(stringToSearch);
                //[{"author":"Loki", "text":"I have an army !", "thread":3,
                //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !",
                //   "thread":3, "createdAt":1404736639715}]
                buf.append("[");
                if (!lm.isEmpty()) {
                    Iterator<Message> it = lm.iterator();
                    Message m = it.next();
                    buf.append(m.toJSON());
                    while (it.hasNext()) {
                        m = it.next();
                        buf.append(", ");
                        buf.append(m.toJSON());
                    }
                }

                buf.append("]");
            }
        }
    }

    if (msg instanceof HttpContent) {
        Root root = Root.getInstance();
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            contentBuf.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //                buf.append("END OF CONTENT\r\n");
            if (currentAction.equals("Add")) {
                addMessageFromContent(contentBuf.toString(), root);
                currentAction = "None";
            }
            LastHttpContent trailer = (LastHttpContent) msg;

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

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

License:Apache License

/**
 * Returns the content length of the specified web socket message.  If the
 * specified message is not a web socket message, {@code -1} is returned.
 *//*  ww  w  .  ja  va2s . co m*/
private static int getWebSocketContentLength(HttpMessage message) {
    // WebSockset messages have constant content-lengths.
    HttpHeaders h = message.headers();
    if (message instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) message;
        if (HttpMethod.GET.equals(req.method()) && h.contains(Names.SEC_WEBSOCKET_KEY1)
                && h.contains(Names.SEC_WEBSOCKET_KEY2)) {
            return 8;
        }
    } else if (message instanceof HttpResponse) {
        HttpResponse res = (HttpResponse) message;
        if (res.status().code() == 101 && h.contains(Names.SEC_WEBSOCKET_ORIGIN)
                && h.contains(Names.SEC_WEBSOCKET_LOCATION)) {
            return 16;
        }
    }

    // Not a web socket message
    return -1;
}

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  . ja va2 s  .c  om
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:cf.component.VcapComponent.java

License:Open Source License

public VcapComponent(CfNats nats, SimpleHttpServer httpServer, String type, List<VarzUpdater> varzUpdaters) {
    this.nats = nats;
    this.type = type;
    this.varzUpdaters = varzUpdaters;

    nats.subscribe(ComponentDiscover.class, new PublicationHandler<ComponentDiscover, ComponentAnnounce>() {
        @Override//from  www .j  ava  2s .  c  o  m
        public void onMessage(Publication<ComponentDiscover, ComponentAnnounce> publication) {
            publication.reply(buildComponentAnnounce());
        }
    });

    nats.publish(buildComponentAnnounce());

    httpServer.addHandler(Pattern.compile("/healthz"), new AuthenticatedJsonTextResponseRequestHandler() {
        @Override
        public String handleAuthenticatedRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
                throws RequestException {
            if (!request.getMethod().equals(HttpMethod.GET)) {
                throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED);
            }
            return "ok\n";
        }
    });

    httpServer.addHandler(Pattern.compile("/varz"), new AuthenticatedJsonTextResponseRequestHandler() {
        @Override
        protected String handleAuthenticatedRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
                throws RequestException {
            if (!request.getMethod().equals(HttpMethod.GET)) {
                throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED);
            }
            final Varz varz = buildVarz();
            try {
                return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(varz);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:cn.wantedonline.puppy.httpserver.component.HttpRequestDecoder.java

License:Apache License

@Override
protected HttpMessage createInvalidMessage() {
    return new HttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/bad-request", true);
}

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  . ja v  a  2 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(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();
}