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:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Adds a POST route./* ww w  .  j  a  v a  2s  .  c  o  m*/
 *
 * @param path    The URL path.
 * @param handler The request handler.
 * @return This WebServer.
 */
public MesosHealthCheckerServer post(final String path, final Handler handler) {
    this.routeTable.addRoute(new Route(HttpMethod.POST, path, handler));
    return this;
}

From source file:com.gw.services.client.HttpsClient.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 w  w . j av a 2 s. c o m
        } 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 = CLIENT_CONTEXT;
    } else {
        sslCtx = null;
    }

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

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

        String requestBody = "{\"productId\": 11,\"userName\": \"caiwei\",\"amount\": 1000}";
        ByteBuf content = Unpooled.copiedBuffer(requestBody.getBytes(CharsetUtil.UTF_8));
        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uri.getRawPath(), content);
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
        // Set some example cookies.
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
                .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.heliosapm.streams.forwarder.HttpJsonOutboundHandler.java

License:Apache License

/**
 * {@inheritDoc}//from   ww w  .j a  va2  s .com
 * @see io.netty.handler.codec.MessageToMessageEncoder#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)
 */
@Override
protected void encode(final ChannelHandlerContext ctx, final ConsumerRecords<String, StreamedMetricValue> msg,
        final List<Object> out) throws Exception {
    final StreamedMetricValue[] smvs = StreamSupport.stream(msg.spliterator(), true)
            .map(new Function<ConsumerRecord<String, StreamedMetricValue>, StreamedMetricValue>() {
                @Override
                public StreamedMetricValue apply(ConsumerRecord<String, StreamedMetricValue> t) {
                    return t.value();
                }

            }).toArray(s -> new StreamedMetricValue[s]);
    final int size = smvs.length;
    final ByteBuf buff = buffManager.buffer(size * 200);

    JSONOps.serializeAndGzip(smvs, buff);
    final int sz = buff.readableBytes();
    final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, postUri,
            buff);
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    request.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
    request.headers().set(HttpHeaderNames.CONTENT_LENGTH, buff.readableBytes());
    out.add(request);

    ctx.executor().execute(new Runnable() {
        public void run() {
            final NonBlockingHashSet<String> hosts = new NonBlockingHashSet<String>();
            StreamSupport.stream(msg.spliterator(), true)
                    .map(new Function<ConsumerRecord<String, StreamedMetricValue>, String>() {
                        @Override
                        public String apply(ConsumerRecord<String, StreamedMetricValue> t) {
                            return t.value().getTags().get("host");
                        }
                    }).forEach(h -> hosts.add(h));
            log.info("Hosts:{}, Size: {}", hosts, sz);
        }
    });
}

From source file:com.heliosapm.streams.metrichub.HubManager.java

License:Apache License

protected HttpRequest buildHttpRequest(final ByteBuf jsonRequest) {
    final String[] endpoints = tsdbEndpoint.getUpServers();
    final URL postUrl = URLHelper.toURL(endpoints[0] + "/query/");
    log.debug("Http Post to [{}]", postUrl);
    final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            postUrl.getPath(), jsonRequest);
    request.headers().set(HttpHeaderNames.HOST, postUrl.getHost());
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
    //      request.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
    request.headers().set(HttpHeaderNames.CONTENT_LENGTH, jsonRequest.readableBytes());
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    return request;
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.interfaces.cheatreport.ReportCheatData.java

License:Open Source License

public ReportCheatData(CheatData cheatInfo, int apiVersion) {
    super(SteamApiConstants.STEAM_METHOD_CHEATREPORTSVC_REPORTCHEATDATA, apiVersion);
    method(HttpMethod.POST);
    urlParam("steamid", cheatInfo.getSteamId());
    urlParam("appid", cheatInfo.getAppId());
    urlParam("pathandfilename", cheatInfo.getFilePath());
    urlParam("webcheaturl", cheatInfo.getWebCheatUrl());
    urlParam("time_now", cheatInfo.getTimeNow());
    urlParam("time_started", cheatInfo.getTimeStarted());
    urlParam("time_stopped", cheatInfo.getTimeStopped());
    urlParam("cheatname", cheatInfo.getCheatName());
    urlParam("game_process_id", cheatInfo.getGameProcessId());
    urlParam("cheat_process_id", cheatInfo.getCheatProcessId());
    urlParam("cheat_param_1", cheatInfo.getCheatParam1());
    urlParam("cheat_param_2", cheatInfo.getCheatParam2());
}

From source file:com.king.platform.net.http.netty.NettyHttpClient.java

License:Apache License

@Override
public HttpClientRequestWithBody createPost(String uri) {
    if (!started.get()) {
        throw new IllegalStateException("Http client is not started!");
    }/*from ww  w.j av  a2s.co m*/

    return new HttpClientRequestBuilder(this, HttpVersion.HTTP_1_1, HttpMethod.POST, uri, confMap);
}

From source file:com.linecorp.armeria.client.http.SimpleHttpRequestBuilder.java

License:Apache License

/**
 * Returns a {@link SimpleHttpRequestBuilder} for a POST request to the given URI,
 * for setting additional HTTP parameters as needed.
 *///from   w w  w  .  ja  va2 s  .c om
public static SimpleHttpRequestBuilder forPost(String uri) {
    return createRequestBuilder(uri, HttpMethod.POST);
}

From source file:com.linecorp.armeria.client.http.SimpleHttpRequestBuilderTest.java

License:Apache License

@Test
public void httpMethods() {
    assertEquals(HttpMethod.GET, SimpleHttpRequestBuilder.forGet("/path").build().method());
    assertEquals(HttpMethod.POST, SimpleHttpRequestBuilder.forPost("/path").build().method());
    assertEquals(HttpMethod.PUT, SimpleHttpRequestBuilder.forPut("/path").build().method());
    assertEquals(HttpMethod.PATCH, SimpleHttpRequestBuilder.forPatch("/path").build().method());
    assertEquals(HttpMethod.DELETE, SimpleHttpRequestBuilder.forDelete("/path").build().method());
    assertEquals(HttpMethod.HEAD, SimpleHttpRequestBuilder.forHead("/path").build().method());
    assertEquals(HttpMethod.OPTIONS, SimpleHttpRequestBuilder.forOptions("/path").build().method());
}

From source file:com.linecorp.armeria.server.thrift.ThriftServiceCodec.java

License:Apache License

private SerializationFormat validateRequestAndDetermineSerializationFormat(Object originalRequest)
        throws InvalidHttpRequestException {
    if (!(originalRequest instanceof HttpRequest)) {
        return defaultSerializationFormat;
    }//from  w  w  w . j  ava  2s.co m
    final SerializationFormat serializationFormat;
    HttpRequest httpRequest = (HttpRequest) originalRequest;
    if (httpRequest.method() != HttpMethod.POST) {
        throw new InvalidHttpRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED,
                HTTP_METHOD_NOT_ALLOWED_EXCEPTION);
    }

    final String contentTypeHeader = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        serializationFormat = SerializationFormat.fromMimeType(contentTypeHeader)
                .orElse(defaultSerializationFormat);
        if (!allowedSerializationFormats.contains(serializationFormat)) {
            throw new InvalidHttpRequestException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                    THRIFT_PROTOCOL_NOT_SUPPORTED);
        }
    } else {
        serializationFormat = defaultSerializationFormat;
    }

    final String acceptHeader = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
    if (acceptHeader != null) {
        // If accept header is present, make sure it is sane. Currently, we do not support accept
        // headers with a different format than the content type header.
        SerializationFormat outputSerializationFormat = SerializationFormat.fromMimeType(acceptHeader)
                .orElse(serializationFormat);
        if (outputSerializationFormat != serializationFormat) {
            throw new InvalidHttpRequestException(HttpResponseStatus.NOT_ACCEPTABLE,
                    ACCEPT_THRIFT_PROTOCOL_MUST_MATCH_CONTENT_TYPE);
        }
    }
    return serializationFormat;
}

From source file:com.linecorp.armeria.server.thrift.THttp2Client.java

License:Apache License

@Override
public void flush() throws TTransportException {
    THttp2ClientInitializer initHandler = new THttp2ClientInitializer();

    Bootstrap b = new Bootstrap();
    b.group(group);/* w ww . ja va 2 s .c  om*/
    b.channel(NioSocketChannel.class);
    b.handler(initHandler);

    Channel ch = null;
    try {
        ch = b.connect(host, port).syncUninterruptibly().channel();
        THttp2ClientHandler handler = initHandler.THttp2ClientHandler;

        // Wait until HTTP/2 upgrade is finished.
        assertTrue(handler.settingsPromise.await(5, TimeUnit.SECONDS));
        handler.settingsPromise.get();

        // Send a Thrift request.
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path,
                Unpooled.wrappedBuffer(out.getArray(), 0, out.length()));
        request.headers().add(HttpHeaderNames.HOST, host);
        request.headers().set(ExtensionHeaderNames.SCHEME.text(), uri.getScheme());
        ch.writeAndFlush(request).sync();

        // Wait until the Thrift response is received.
        assertTrue(handler.responsePromise.await(5, TimeUnit.SECONDS));
        ByteBuf response = handler.responsePromise.get();

        // Pass the received Thrift response to the Thrift client.
        final byte[] array = new byte[response.readableBytes()];
        response.readBytes(array);
        in = new TMemoryInputTransport(array);
        response.release();
    } catch (Exception e) {
        throw new TTransportException(TTransportException.UNKNOWN, e);
    } finally {
        if (ch != null) {
            ch.close();
        }
    }
}