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

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

Introduction

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

Prototype

HttpMethod POST

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

Click Source Link

Document

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

Usage

From source file:org.elasticsearch.http.netty4.Netty4HttpClient.java

License:Apache License

@SafeVarargs // Safe not because it doesn't do anything with the type parameters but because it won't leak them into other methods.
public final Collection<FullHttpResponse> post(SocketAddress remoteAddress,
        Tuple<String, CharSequence>... urisAndBodies) throws InterruptedException {
    return processRequestsWithBody(HttpMethod.POST, remoteAddress, urisAndBodies);
}

From source file:org.elasticsearch.http.netty4.Netty4HttpServerTransportTests.java

License:Apache License

/**
 * Test that {@link Netty4HttpServerTransport} supports the "Expect: 100-continue" HTTP header
 */// w  w w .ja  v a  2  s.c  o  m
public void testExpectContinueHeader() throws Exception {
    try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(Settings.EMPTY, networkService,
            bigArrays, threadPool)) {
        transport.httpServerAdapter((request, channel, context) -> channel.sendResponse(
                new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done"))));
        transport.start();
        InetSocketTransportAddress remoteAddress = (InetSocketTransportAddress) randomFrom(
                transport.boundAddress().boundAddresses());

        try (Netty4HttpClient client = new Netty4HttpClient()) {
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
            HttpUtil.set100ContinueExpected(request, true);
            HttpUtil.setContentLength(request, 10);

            FullHttpResponse response = client.post(remoteAddress.address(), request);
            assertThat(response.status(), is(HttpResponseStatus.CONTINUE));

            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/",
                    Unpooled.EMPTY_BUFFER);
            response = client.post(remoteAddress.address(), request);
            assertThat(response.status(), is(HttpResponseStatus.OK));
            assertThat(new String(ByteBufUtil.getBytes(response.content()), StandardCharsets.UTF_8),
                    is("done"));
        }
    }
}

From source file:org.elasticsearch.http.nio.HttpReadWriteHandlerTests.java

License:Apache License

public void testDecodeHttpRequestContentLengthToLongGeneratesOutboundMessage() throws IOException {
    String uri = "localhost:9090/" + randomAlphaOfLength(8);
    io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
            HttpMethod.POST, uri, false);
    HttpUtil.setContentLength(httpRequest, 1025);
    HttpUtil.setKeepAlive(httpRequest, false);

    ByteBuf buf = requestEncoder.encode(httpRequest);
    try {/*from  ww  w . j  a  va 2s  .  c  om*/
        handler.consumeReads(toChannelBuffer(buf));
    } finally {
        buf.release();
    }
    verify(transport, times(0)).incomingRequestError(any(), any(), any());
    verify(transport, times(0)).incomingRequest(any(), any());

    List<FlushOperation> flushOperations = handler.pollFlushOperations();
    assertFalse(flushOperations.isEmpty());

    FlushOperation flushOperation = flushOperations.get(0);
    FullHttpResponse response = responseDecoder
            .decode(Unpooled.wrappedBuffer(flushOperation.getBuffersToWrite()));
    try {
        assertEquals(HttpVersion.HTTP_1_1, response.protocolVersion());
        assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());

        flushOperation.getListener().accept(null, null);
        // Since we have keep-alive set to false, we should close the channel after the response has been
        // flushed
        verify(nioHttpChannel).close();
    } finally {
        response.release();
    }
}

From source file:org.elasticsearch.http.nio.NioHttpRequest.java

License:Apache License

@Override
public RestRequest.Method method() {
    HttpMethod httpMethod = request.method();
    if (httpMethod == HttpMethod.GET)
        return RestRequest.Method.GET;

    if (httpMethod == HttpMethod.POST)
        return RestRequest.Method.POST;

    if (httpMethod == HttpMethod.PUT)
        return RestRequest.Method.PUT;

    if (httpMethod == HttpMethod.DELETE)
        return RestRequest.Method.DELETE;

    if (httpMethod == HttpMethod.HEAD) {
        return RestRequest.Method.HEAD;
    }//from  w w w .  ja va  2  s.  com

    if (httpMethod == HttpMethod.OPTIONS) {
        return RestRequest.Method.OPTIONS;
    }

    if (httpMethod == HttpMethod.PATCH) {
        return RestRequest.Method.PATCH;
    }

    if (httpMethod == HttpMethod.TRACE) {
        return RestRequest.Method.TRACE;
    }

    if (httpMethod == HttpMethod.CONNECT) {
        return RestRequest.Method.CONNECT;
    }

    throw new IllegalArgumentException("Unexpected http method: " + httpMethod);
}

From source file:org.elasticsearch.http.nio.NioHttpServerTransportTests.java

License:Apache License

private void runExpectHeaderTest(final Settings settings, final String expectation, final int contentLength,
        final HttpResponseStatus expectedStatus) throws InterruptedException {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {
        @Override/*w  w w .ja  v  a2s .  co m*/
        public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
            channel.sendResponse(
                    new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done")));
        }

        @Override
        public void dispatchBadRequest(RestRequest request, RestChannel channel, ThreadContext threadContext,
                Throwable cause) {
            throw new AssertionError();
        }
    };
    try (NioHttpServerTransport transport = new NioHttpServerTransport(settings, networkService, bigArrays,
            pageRecycler, threadPool, xContentRegistry(), dispatcher)) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        try (NioHttpClient client = new NioHttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                    "/");
            request.headers().set(HttpHeaderNames.EXPECT, expectation);
            HttpUtil.setContentLength(request, contentLength);

            final FullHttpResponse response = client.post(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(expectedStatus));
                if (expectedStatus.equals(HttpResponseStatus.CONTINUE)) {
                    final FullHttpRequest continuationRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                            HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER);
                    final FullHttpResponse continuationResponse = client.post(remoteAddress.address(),
                            continuationRequest);
                    try {
                        assertThat(continuationResponse.status(), is(HttpResponseStatus.OK));
                        assertThat(new String(ByteBufUtil.getBytes(continuationResponse.content()),
                                StandardCharsets.UTF_8), is("done"));
                    } finally {
                        continuationResponse.release();
                    }
                }
            } finally {
                response.release();
            }
        }
    }
}

From source file:org.fiware.kiara.transport.http.HttpTransportFactory.java

License:Open Source License

private ListenableFuture<Transport> openConnection(URI uri, Map<String, Object> settings) throws IOException {
    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.ja  v  a2 s  . c  om*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        throw new IOException("Only HTTP(S) is supported.");
    }

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

    // Configure the client.
    final SettableFuture<Transport> onConnectionActive = SettableFuture.create();
    final HttpHandler clientHandler = new HttpHandler(this, uri, HttpMethod.POST, null);
    clientHandler.setConnectionListener(new TransportConnectionListener() {

        @Override
        public void onConnectionOpened(TransportImpl connection) {
            clientHandler.setConnectionListener(null);
            onConnectionActive.set(connection);
        }

        @Override
        public void onConnectionClosed(TransportImpl connection) {

        }
    });

    Bootstrap b = new Bootstrap();
    b.group(getEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new HttpClientInitializer(sslCtx, clientHandler));
    b.connect(host, port);

    return onConnectionActive;
}

From source file:org.ftccommunity.ftcxtensible.networking.http.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String page;/*from w  ww  .  java2s  .c  om*/

        if (req.getMethod() == HttpMethod.POST) {
            LinkedList<InterfaceHttpData> postData = new LinkedList<>();
            HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(
                    new DefaultHttpDataFactory(false), req);
            postRequestDecoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    postData.add(data);
                }
            }
            context.addPostData(postData);
        }

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        HttpResponseStatus responseStatus = OK;
        String uri = (req.getUri().equals("/") ? context.getServerSettings().getIndex() : req.getUri());
        if (uri.equals(context.getServerSettings().getHardwareMapJsonPage())) {
            GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization();
            Gson gson = gsonBuilder.create();
            HardwareMap hardwareMap = context.getHardwareMap();
            page = gson.toJson(ImmutableSet.copyOf(hardwareMap.dcMotor));
        } else if (uri.equals(context.getServerSettings().getLogPage())) {
            page = context.getStatus().getLog();
        } else {
            if (cache.containsKey(uri)) {
                page = cache.get(uri);
                responseStatus = NOT_MODIFIED;
            } else {
                try {
                    page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8);
                } catch (FileNotFoundException e) {
                    Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri);
                    page = "File Not Found!";
                    responseStatus = NOT_FOUND;
                } catch (IOException e) {
                    page = "An Error Occurred!\n" + e.toString();
                    responseStatus = NOT_FOUND;
                    Log.e("NET_OP_MODE::", e.toString(), e);
                }
                cache.put(uri, page);
            }
        }

        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus,
                Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8)));

        String extension = MimeTypeMap.getFileExtensionFromUrl(uri);
        String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

        response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension))
                + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8"));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:org.ftccommunity.ftcxtensible.networking.http.RobotHttpServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String page;/*from  w w  w  . j  a  v a  2  s. com*/

        if (req.getMethod() == HttpMethod.POST) {
            LinkedList<InterfaceHttpData> postData = new LinkedList<>();
            HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(
                    new DefaultHttpDataFactory(false), req);
            postRequestDecoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    postData.add(data);
                }
            }
            context.addPostData(postData);
        }

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        HttpResponseStatus responseStatus = OK;
        String uri = (req.getUri().equals("/") ? context.serverSettings().getIndex() : req.getUri());
        if (uri.equals(context.serverSettings().getHardwareMapJsonPage())) {
            GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization();
            Gson gson = gsonBuilder.create();
            ExtensibleHardwareMap hardwareMap = context.hardwareMap();
            page = gson.toJson(hardwareMap.dcMotors());
        } else if (uri.equals(context.serverSettings().getLogPage())) {
            page = context.status().getLog();
        } else {
            if (cache.containsKey(uri)) {
                page = cache.get(uri);
                responseStatus = NOT_MODIFIED;
            } else {
                try {
                    page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8);
                } catch (FileNotFoundException e) {
                    Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri);
                    page = "File Not Found!";
                    responseStatus = NOT_FOUND;
                } catch (IOException e) {
                    page = "An Error Occurred!\n" + e.toString();
                    responseStatus = NOT_FOUND;
                    Log.e("NET_OP_MODE::", e.toString(), e);
                }
                cache.put(uri, page);
            }
        }

        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus,
                Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8)));

        String extension = MimeTypeMap.getFileExtensionFromUrl(uri);
        String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

        response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension))
                + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8"));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:org.glowroot.common2.repo.util.HttpClient.java

License:Apache License

private String postOrGet(String url, byte /*@Nullable*/ [] content, @Nullable String contentType,
        final HttpProxyConfig httpProxyConfig, final @Nullable String passwordOverride) throws Exception {
    URI uri = new URI(url);
    String scheme = checkNotNull(uri.getScheme());
    final boolean ssl = scheme.equalsIgnoreCase("https");
    final String host = checkNotNull(uri.getHost());
    final int port;
    if (uri.getPort() == -1) {
        port = ssl ? 443 : 80;//  w ww  .j  av a 2s . c  o m
    } else {
        port = uri.getPort();
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        // TODO follow netty proxy support at https://github.com/netty/netty/issues/1133
        final HttpProxyHandler httpProxyHandler = newHttpProxyHandlerIfNeeded(httpProxyConfig,
                passwordOverride);
        final HttpClientHandler handler = new HttpClientHandler();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (httpProxyHandler != null) {
                    p.addLast(httpProxyHandler);
                }
                if (ssl) {
                    SslContext sslContext = SslContextBuilder.forClient().build();
                    p.addLast(sslContext.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new HttpObjectAggregator(1048576));
                p.addLast(handler);
            }
        });
        if (!httpProxyConfig.host().isEmpty()) {
            // name resolution should be performed by the proxy server in case some proxy rules
            // depend on the remote hostname
            bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
        }
        HttpRequest request;
        if (content == null) {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
        } else {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(),
                    Unpooled.wrappedBuffer(content));
            request.headers().set(HttpHeaderNames.CONTENT_TYPE, checkNotNull(contentType));
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length);
        }
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        Channel ch = bootstrap.connect(host, port).sync().channel();
        if (httpProxyHandler != null) {
            // this line is needed to capture and throw connection exception properly
            httpProxyHandler.connectFuture().get();
        }
        ch.writeAndFlush(request).get();
        ch.closeFuture().sync().get();
        Throwable exception = handler.exception;
        if (exception != null) {
            Throwables.propagateIfPossible(exception, Exception.class);
            throw new Exception(exception);
        }
        HttpResponseStatus responseStatus = checkNotNull(handler.responseStatus);
        int statusCode = responseStatus.code();
        if (statusCode == 429) {
            throw new TooManyRequestsHttpResponseException();
        } else if (statusCode < 200 || statusCode >= 300) {
            throw new IOException("Unexpected response status code: " + statusCode);
        }
        return checkNotNull(handler.responseContent);
    } finally {
        group.shutdownGracefully(0, 10, SECONDS).get();
    }
}

From source file:org.graylog2.inputs.transports.netty.HttpHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    final Channel channel = ctx.channel();
    final boolean keepAlive = HttpUtil.isKeepAlive(request);
    final HttpVersion httpRequestVersion = request.protocolVersion();
    final String origin = request.headers().get(HttpHeaderNames.ORIGIN);

    // to allow for future changes, let's be at least a little strict in what we accept here.
    if (HttpMethod.OPTIONS.equals(request.method())) {
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.OK, origin);
        return;/*from  w ww .  j  a  v  a  2  s  .co m*/
    } else if (!HttpMethod.POST.equals(request.method())) {
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.METHOD_NOT_ALLOWED, origin);
        return;
    }

    final boolean correctPath = "/gelf".equals(request.uri());
    if (correctPath && request instanceof FullHttpRequest) {
        final FullHttpRequest fullHttpRequest = (FullHttpRequest) request;
        final ByteBuf buffer = fullHttpRequest.content();

        // send on to raw message handler
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.ACCEPTED, origin);
        ctx.fireChannelRead(buffer);
    } else {
        writeResponse(channel, keepAlive, httpRequestVersion, HttpResponseStatus.NOT_FOUND, origin);
    }
}