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:io.aos.netty5.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null,
            IdentityCipherSuiteFilter.INSTANCE,
            Arrays.asList(SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
            JettyNpnSslEngineWrapper.instance(), 0, 0);

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from w  w w . ja v a2s .  c om
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        request.headers().set(HttpHeaders.Names.HOST, HOST);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}

From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (!accept(req)) {
            ctx.fireChannelRead(msg);/*from w w w  . ja  va 2  s.  co  m*/
            return;
        }
        if (req.getMethod() == HttpMethod.GET
                && req.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)) {
            // Because WebSocketServerHandshaker requires FullHttpRequest
            FullHttpRequest wsRequest = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(),
                    req.getUri());
            wsRequest.headers().set(req.headers());
            wsReqMap.put(ctx.channel(), wsRequest);
            // Set timeout to avoid memory leak
            ctx.pipeline().addFirst(new ReadTimeoutHandler(5));
        } else {
            NettyServerHttpExchange http = new NettyServerHttpExchange(ctx, req);
            httpMap.put(ctx.channel(), http);
            httpActions.fire(http);
        }
    } else if (msg instanceof HttpContent) {
        FullHttpRequest wsReq = wsReqMap.get(ctx.channel());
        if (wsReq != null) {
            wsReq.content().writeBytes(((HttpContent) msg).content());
            if (msg instanceof LastHttpContent) {
                wsReqMap.remove(ctx.channel());
                // Cancel timeout
                ctx.pipeline().remove(ReadTimeoutHandler.class);
                WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(
                        getWebSocketLocation(ctx.pipeline(), wsReq), null, true);
                WebSocketServerHandshaker handshaker = factory.newHandshaker(wsReq);
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    handshaker.handshake(ctx.channel(), wsReq);
                    NettyServerWebSocket ws = new NettyServerWebSocket(ctx, wsReq, handshaker);
                    wsMap.put(ctx.channel(), ws);
                    wsActions.fire(ws);
                }
            }
        } else {
            NettyServerHttpExchange http = httpMap.get(ctx.channel());
            if (http != null) {
                http.handleChunk((HttpContent) msg);
            }
        }
    } else if (msg instanceof WebSocketFrame) {
        NettyServerWebSocket ws = wsMap.get(ctx.channel());
        if (ws != null) {
            ws.handleFrame((WebSocketFrame) msg);
        }
    }
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private boolean possibleRedirect(HttpRequest request, String index, String digest) {
    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.HEAD)
            || (method.equals(HttpMethod.PUT) && HttpUtil.is100ContinueExpected(request))) {
        String redirectAddress;/*from w  w  w .  ja v  a 2 s .c  om*/
        try {
            redirectAddress = blobService.getRedirectAddress(index, digest);
        } catch (MissingHTTPEndpointException ex) {
            simpleResponse(HttpResponseStatus.BAD_GATEWAY);
            return true;
        }

        if (redirectAddress != null) {
            LOGGER.trace("redirectAddress: {}", redirectAddress);
            sendRedirect(activeScheme + redirectAddress);
            return true;
        }
    }
    return false;
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void handleBlobRequest(HttpRequest request, @Nullable HttpContent content) throws IOException {
    if (possibleRedirect(request, index, digest)) {
        reset();//from  w w  w  . ja v a 2  s . c  o m
        return;
    }

    HttpMethod method = request.method();
    if (method.equals(HttpMethod.GET)) {
        get(request, index, digest);
        reset();
    } else if (method.equals(HttpMethod.HEAD)) {
        head(index, digest);
        reset();
    } else if (method.equals(HttpMethod.PUT)) {
        put(content, index, digest);
    } else if (method.equals(HttpMethod.DELETE)) {
        delete(index, digest);
        reset();
    } else {
        simpleResponse(HttpResponseStatus.METHOD_NOT_ALLOWED);
        reset();
    }
}

From source file:io.example.UploadClient.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 ww  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 {
    // 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(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);
    System.out.println("Sent formget");

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

    return entries;
}

From source file:io.gatling.http.client.ahc.oauth.OAuthSignatureCalculatorTest.java

License:Apache License

@Test
void testGetCalculateSignature() throws NoSuchAlgorithmException, InvalidKeyException {

    List<Param> queryParams = new ArrayList<>();
    queryParams.add(new Param("file", "vacation.jpg"));
    queryParams.add(new Param("size", "original"));

    Request request = new RequestBuilder(HttpMethod.GET, Uri.create("http://photos.example.net/photos"))
            .setQueryParams(queryParams).build();

    String signature = new OAuthSignatureCalculatorInstance().computeSignature(
            new ConsumerKey(CONSUMER_KEY, CONSUMER_SECRET), new RequestToken(TOKEN_KEY, TOKEN_SECRET),
            request.getMethod(), request.getUri(), null, TIMESTAMP, NONCE);

    assertEquals("tR3+Ty81lMeYAr/Fid0kMTYa/WM=", signature);
}

From source file:io.gatling.http.client.ahc.oauth.OAuthSignatureCalculatorTest.java

License:Apache License

@Test
void testGetWithRequestBuilder() throws Exception {
    StaticOAuthSignatureCalculator calc = new StaticOAuthSignatureCalculator(
            new ConsumerKey(CONSUMER_KEY, CONSUMER_SECRET), new RequestToken(TOKEN_KEY, TOKEN_SECRET), NONCE,
            TIMESTAMP);/*from  ww w  .j ava  2s . c  o  m*/

    List<Param> queryParams = new ArrayList<>();
    queryParams.add(new Param("file", "vacation.jpg"));
    queryParams.add(new Param("size", "original"));

    final Request req = new RequestBuilder(HttpMethod.GET, Uri.create("http://photos.example.net/photos"))
            .setQueryParams(queryParams).build();

    final List<Param> params = req.getUri().getEncodedQueryParams();
    assertEquals(2, params.size());

    // From the signature tester, the URL should look like:
    // normalized parameters:
    // file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original
    // signature base string:
    // GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal
    // signature: tR3+Ty81lMeYAr/Fid0kMTYa/WM=
    // Authorization header: OAuth
    // realm="",oauth_version="1.0",oauth_consumer_key="dpf43f3p2l4k3l03",oauth_token="nnch734d00sl2jdk",oauth_timestamp="1191242096",oauth_nonce="kllo9940pd9333jh",oauth_signature_method="HMAC-SHA1",oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"

    calc.sign(req);

    String authHeader = req.getHeaders().get(AUTHORIZATION);
    Matcher m = Pattern.compile("oauth_signature=\"(.+?)\"").matcher(authHeader);
    assertTrue(m.find());
    String encodedSig = m.group(1);
    String sig = URLDecoder.decode(encodedSig, "UTF-8");

    assertEquals("tR3+Ty81lMeYAr/Fid0kMTYa/WM=", sig);
    assertEquals("http://photos.example.net/photos?file=vacation.jpg&size=original", req.getUri().toUrl());
}

From source file:io.gatling.http.client.ahc.oauth.OAuthSignatureCalculatorTest.java

License:Apache License

@Test
void testGetWithRequestBuilderAndQuery() throws Exception {
    StaticOAuthSignatureCalculator calc = //
            new StaticOAuthSignatureCalculator(//
                    new ConsumerKey(CONSUMER_KEY, CONSUMER_SECRET), new RequestToken(TOKEN_KEY, TOKEN_SECRET),
                    NONCE, TIMESTAMP);/*from  www  .j a  v  a2  s  .  c  om*/

    final Request req = new RequestBuilder(HttpMethod.GET,
            Uri.create("http://photos.example.net/photos?file=vacation.jpg&size=original")).build();

    final List<Param> params = req.getUri().getEncodedQueryParams();
    assertEquals(2, params.size());

    // From the signature tester, the URL should look like:
    // normalized parameters:
    // file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original
    // signature base string:
    // GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal
    // signature: tR3+Ty81lMeYAr/Fid0kMTYa/WM=
    // Authorization header: OAuth
    // realm="",oauth_version="1.0",oauth_consumer_key="dpf43f3p2l4k3l03",oauth_token="nnch734d00sl2jdk",oauth_timestamp="1191242096",oauth_nonce="kllo9940pd9333jh",oauth_signature_method="HMAC-SHA1",oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"

    calc.sign(req);
    String authHeader = req.getHeaders().get(AUTHORIZATION);
    Matcher m = Pattern.compile("oauth_signature=\"(.+?)\"").matcher(authHeader);
    assertTrue(m.find());
    String encodedSig = m.group(1);
    String sig = URLDecoder.decode(encodedSig, "UTF-8");

    assertEquals("tR3+Ty81lMeYAr/Fid0kMTYa/WM=", sig);
    assertEquals("http://photos.example.net/photos?file=vacation.jpg&size=original", req.getUri().toUrl());
    assertEquals(

            "OAuth oauth_consumer_key=\"dpf43f3p2l4k3l03\", oauth_token=\"nnch734d00sl2jdk\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D\", oauth_timestamp=\"1191242096\", oauth_nonce=\"kllo9940pd9333jh\", oauth_version=\"1.0\"",
            authHeader);
}

From source file:io.gatling.http.client.ahc.oauth.OAuthSignatureCalculatorTest.java

License:Apache License

@Test
void testWithNullRequestToken() throws NoSuchAlgorithmException {

    final Request request = new RequestBuilder(HttpMethod.GET,
            Uri.create("http://photos.example.net/photos?file=vacation.jpg&size=original")).build();

    String signatureBaseString = new OAuthSignatureCalculatorInstance().signatureBaseString(//
            new ConsumerKey("9djdj82h48djs9d2", CONSUMER_SECRET), new RequestToken(null, null),
            request.getMethod(), request.getUri(), null, 137131201,
            Utf8UrlEncoder.percentEncodeQueryElement("ZLc92RAkooZcIO/0cctl0Q==")).toString();

    assertEquals("GET&" + "http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26"
            + "oauth_consumer_key%3D9djdj82h48djs9d2%26"
            + "oauth_nonce%3DZLc92RAkooZcIO%252F0cctl0Q%253D%253D%26" + "oauth_signature_method%3DHMAC-SHA1%26"
            + "oauth_timestamp%3D137131201%26" + "oauth_version%3D1.0%26size%3Doriginal", signatureBaseString);
}

From source file:io.gatling.http.client.ahc.oauth.OAuthSignatureCalculatorTest.java

License:Apache License

@Test
void testWithStarQueryParameterValue() throws NoSuchAlgorithmException {
    final Request request = new RequestBuilder(HttpMethod.GET,
            Uri.create("http://term.ie/oauth/example/request_token.php?testvalue=*")).build();

    String signatureBaseString = new OAuthSignatureCalculatorInstance()
            .signatureBaseString(new ConsumerKey("key", "secret"), new RequestToken(null, null),
                    request.getMethod(), request.getUri(), null, 1469019732, "6ad17f97334700f3ec2df0631d5b7511")
            .toString();/*from   ww w.  j a  v  a2 s .  c o m*/

    assertEquals("GET&" + "http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&"
            + "oauth_consumer_key%3Dkey%26" + "oauth_nonce%3D6ad17f97334700f3ec2df0631d5b7511%26"
            + "oauth_signature_method%3DHMAC-SHA1%26" + "oauth_timestamp%3D1469019732%26"
            + "oauth_version%3D1.0%26" + "testvalue%3D%252A", signatureBaseString);
}