Search in sources :

Example 31 with HttpRequest

use of io.netty.handler.codec.http.HttpRequest in project netty by netty.

the class SpdyClient method main.

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN, // 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.SPDY_3_1, ApplicationProtocolNames.HTTP_1_1)).build();
    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        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(HttpHeaderNames.HOST, HOST);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.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 {
        workerGroup.shutdownGracefully();
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) ApplicationProtocolConfig(io.netty.handler.ssl.ApplicationProtocolConfig)

Example 32 with HttpRequest

use of io.netty.handler.codec.http.HttpRequest in project netty by netty.

the class HttpUploadClient method formget.

/**
     * 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
     **/
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();
}
Also used : DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) URI(java.net.URI) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder)

Example 33 with HttpRequest

use of io.netty.handler.codec.http.HttpRequest in project async-http-client by AsyncHttpClient.

the class BasicHttpsTest method multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy.

@Test
public void multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy() throws Throwable {
    logger.debug(">>> multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy");
    KeepAliveStrategy keepAliveStrategy = new KeepAliveStrategy() {

        @Override
        public boolean keepAlive(Request ahcRequest, HttpRequest nettyRequest, HttpResponse nettyResponse) {
            return !ahcRequest.getUri().isSecured();
        }
    };
    withClient(config().setSslEngineFactory(createSslEngineFactory()).setKeepAliveStrategy(keepAliveStrategy)).run(client -> {
        withServer(server).run(server -> {
            server.enqueueEcho();
            server.enqueueEcho();
            server.enqueueEcho();
            String body = "hello there";
            client.preparePost(getTargetUrl()).setBody(body).setHeader(CONTENT_TYPE, "text/html").execute();
            client.preparePost(getTargetUrl()).setBody(body).setHeader(CONTENT_TYPE, "text/html").execute();
            Response response = client.preparePost(getTargetUrl()).setBody(body).setHeader(CONTENT_TYPE, "text/html").execute().get();
            assertEquals(response.getResponseBody(), body);
        });
    });
    logger.debug("<<< multipleConcurrentPostRequestsOverHttpsWithDisabledKeepAliveStrategy");
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpResponse(io.netty.handler.codec.http.HttpResponse) KeepAliveStrategy(org.asynchttpclient.channel.KeepAliveStrategy) Test(org.testng.annotations.Test) HttpTest(org.asynchttpclient.testserver.HttpTest)

Example 34 with HttpRequest

use of io.netty.handler.codec.http.HttpRequest in project async-http-client by AsyncHttpClient.

the class NettyConnectListener method writeRequest.

private void writeRequest(Channel channel) {
    if (futureIsAlreadyCancelled(channel)) {
        return;
    }
    if (LOGGER.isDebugEnabled()) {
        HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
        LOGGER.debug("Using new Channel '{}' for '{}' to '{}'", channel, httpRequest.method(), httpRequest.uri());
    }
    Channels.setAttribute(channel, future);
    channelManager.registerOpenChannel(channel, partitionKey);
    future.attachChannel(channel, false);
    requestSender.writeRequest(future, channel);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest)

Example 35 with HttpRequest

use of io.netty.handler.codec.http.HttpRequest in project async-http-client by AsyncHttpClient.

the class NettyRequestSender method sendRequestWithOpenChannel.

private <T> ListenableFuture<T> sendRequestWithOpenChannel(Request request, ProxyServer proxy, NettyResponseFuture<T> future, AsyncHandler<T> asyncHandler, Channel channel) {
    if (asyncHandler instanceof AsyncHandlerExtensions)
        AsyncHandlerExtensions.class.cast(asyncHandler).onConnectionPooled(channel);
    TimeoutsHolder timeoutsHolder = scheduleRequestTimeout(future);
    timeoutsHolder.initRemoteAddress((InetSocketAddress) channel.remoteAddress());
    future.setChannelState(ChannelState.POOLED);
    future.attachChannel(channel, false);
    if (LOGGER.isDebugEnabled()) {
        HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
        LOGGER.debug("Using open Channel {} for {} '{}'", channel, httpRequest.method(), httpRequest.uri());
    }
    // channelInactive might be called between isChannelValid and writeRequest
    // so if we don't store the Future now, channelInactive won't perform handleUnexpectedClosedChannel
    Channels.setAttribute(channel, future);
    if (Channels.isChannelValid(channel)) {
        writeRequest(future, channel);
    } else {
        // bad luck, the channel was closed in-between
        // there's a very good chance onClose was already notified but the
        // future wasn't already registered
        handleUnexpectedClosedChannel(channel, future);
    }
    return future;
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) AsyncHandlerExtensions(org.asynchttpclient.handler.AsyncHandlerExtensions) TimeoutsHolder(org.asynchttpclient.netty.timeout.TimeoutsHolder)

Aggregations

HttpRequest (io.netty.handler.codec.http.HttpRequest)114 Test (org.junit.Test)38 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)29 HttpResponse (io.netty.handler.codec.http.HttpResponse)26 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)22 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)19 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)17 ByteBuf (io.netty.buffer.ByteBuf)13 HttpContent (io.netty.handler.codec.http.HttpContent)13 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)13 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)12 URI (java.net.URI)12 Channel (io.netty.channel.Channel)10 ChannelFuture (io.netty.channel.ChannelFuture)9 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)9 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)9 Map (java.util.Map)9 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)7 Endpoint (com.nike.riposte.server.http.Endpoint)6 Bootstrap (io.netty.bootstrap.Bootstrap)6