Example usage for io.netty.handler.codec.http DefaultFullHttpRequest DefaultFullHttpRequest

List of usage examples for io.netty.handler.codec.http DefaultFullHttpRequest DefaultFullHttpRequest

Introduction

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

Prototype

public DefaultFullHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri) 

Source Link

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 ww w. j  a v a  2 s  .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 {
    // 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:HttpUploadClient.java

License:Apache License

/**
 * Multipart example/*from   www .j  ava 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:catacumba.websocket.internal.WebSocketEngine.java

License:Apache License

@SuppressWarnings("deprecation")
public static <T> void connect(final Context context, String path, int maxLength,
        final WebSocketHandler<T> handler) {
    PublicAddress publicAddress = context.get(PublicAddress.class);
    URI address = publicAddress.get(context);
    URI httpPath = address.resolve(path);

    URI wsPath;/*from w ww.  j  a va 2s .c o  m*/
    try {
        wsPath = new URI("ws", httpPath.getUserInfo(), httpPath.getHost(), httpPath.getPort(),
                httpPath.getPath(), httpPath.getQuery(), httpPath.getFragment());
    } catch (URISyntaxException e) {
        throw uncheck(e);
    }

    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(wsPath.toString(), null,
            true, maxLength);

    Request request = context.getRequest();
    HttpMethod method = valueOf(request.getMethod().getName());
    FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri());
    nettyRequest.headers().add(SEC_WEBSOCKET_VERSION, request.getHeaders().get(SEC_WEBSOCKET_VERSION));
    nettyRequest.headers().add(SEC_WEBSOCKET_KEY, request.getHeaders().get(SEC_WEBSOCKET_KEY));

    final WebSocketServerHandshaker handshaker = factory.newHandshaker(nettyRequest);

    final DirectChannelAccess directChannelAccess = context.getDirectChannelAccess();
    final Channel channel = directChannelAccess.getChannel();

    if (!channel.config().isAutoRead()) {
        channel.config().setAutoRead(true);
    }

    handshaker.handshake(channel, nettyRequest)
            .addListener(new HandshakeFutureListener<>(context, handshaker, handler));
}

From source file:ccwihr.client.t2.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    //        // Configure SSL.
    //        final SslContext sslCtx;
    //        if (SSL) {
    //            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    //            sslCtx = SslContextBuilder.forClient()
    //                .sslProvider(provider)
    //                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
    //                 * Please refer to the HTTP/2 specification for cipher requirements. */
    //                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
    //                .trustManager(InsecureTrustManagerFactory.INSTANCE)
    //                .applicationProtocolConfig(new ApplicationProtocolConfig(
    //                    Protocol.ALPN,
    //                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
    //                    SelectorFailureBehavior.NO_ADVERTISE,
    //                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
    //                    SelectedListenerFailureBehavior.ACCEPT,
    //                    ApplicationProtocolNames.HTTP_2,
    //                    ApplicationProtocolNames.HTTP_1_1))
    //                .build();
    //        } else {
    //            sslCtx = null;
    //        }/*from   w  w  w . j  ava2 s  .c o  m*/

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    //        Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);
    Http2ClientInitializer initializer = new Http2ClientInitializer(null, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

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

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

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

From source file:com.cmz.http.snoop.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//w ww  .  j  a  v  a 2s . c om
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandlerTest.java

License:Apache License

@Test
public void shouldAuthorizeRequest() throws Exception {
    prepareAuthorizationListener(true, null);

    channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, TEST_URI));
    // then/* w w  w .  j  a v a 2s . c om*/
    Object in = channel.readInbound();
    assertTrue(in instanceof DefaultFullHttpRequest);
    DefaultFullHttpRequest req = (DefaultFullHttpRequest) in;
    assertEquals(1, req.refCnt());

}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandlerTest.java

License:Apache License

@Test
public void shouldNotAuthorizeRequest() throws Exception {
    prepareAuthorizationListener(false, null);

    channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, TEST_URI));
    // then/*from  w ww. ja  v a2  s .co m*/
    Object out = channel.readOutbound();
    assertTrue(out instanceof DefaultHttpResponse);
    DefaultHttpResponse res = (DefaultHttpResponse) out;
    assertEquals(HttpResponseStatus.UNAUTHORIZED, res.getStatus());
}

From source file:com.couchbase.client.core.endpoint.query.QueryHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final QueryRequest msg) throws Exception {
    FullHttpRequest request;//ww  w  .  j a  v  a  2s. com

    if (msg instanceof GenericQueryRequest) {
        GenericQueryRequest queryRequest = (GenericQueryRequest) msg;
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/query");
        request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
        if (queryRequest.isJsonFormat()) {
            request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        }
        ByteBuf query = ctx.alloc().buffer(((GenericQueryRequest) msg).query().length());
        query.writeBytes(((GenericQueryRequest) msg).query().getBytes(CHARSET));
        request.headers().add(HttpHeaders.Names.CONTENT_LENGTH, query.readableBytes());
        request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));
        request.content().writeBytes(query);
        query.release();
    } else if (msg instanceof KeepAliveRequest) {
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/admin/ping");
        request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
        request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));
        return request;
    } else {
        throw new IllegalArgumentException("Unknown incoming QueryRequest type " + msg.getClass());
    }

    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());
    return request;
}

From source file:com.couchbase.client.core.endpoint.view.ViewCodec.java

License:Open Source License

private HttpRequest handleViewQueryRequest(final ViewQueryRequest msg) {
    StringBuilder requestBuilder = new StringBuilder();
    requestBuilder.append("/").append(msg.bucket()).append("/_design/");
    requestBuilder.append(msg.development() ? "dev_" + msg.design() : msg.design());
    requestBuilder.append("/_view/").append(msg.view());
    if (msg.query() != null && !msg.query().isEmpty()) {
        requestBuilder.append("?").append(msg.query());
    }/*  w  ww. j  av a  2s. co m*/
    return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, requestBuilder.toString());
}

From source file:com.digisky.innerproxy.testclient.HttpSnoopClient.java

License:Apache License

public static void test(Channel ch, String uri, String sjson) {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.setMethod(HttpMethod.POST);/*www  .  j av a  2  s  . co m*/
    request.setUri("/" + uri);
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(request, false);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // false => not multipart
      //***********************************************************************
    try {
        bodyRequestEncoder.addBodyAttribute("val", sjson);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //***********************************************************************
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ch.writeAndFlush(request);
    try {
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}