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:io.galeb.router.sync.HttpClient.java

License:Open Source License

public void post(String url, String etag) {
    RequestBuilder requestBuilder = new RequestBuilder().setUrl(url).setMethod(HttpMethod.POST.name())
            .setHeader(IF_NONE_MATCH_STRING, etag).setHeader(X_GALEB_GROUP_ID, GROUP_ID)
            .setHeader(X_GALEB_ENVIRONMENT, ENVIRONMENT_NAME).setHeader(X_GALEB_LOCAL_IP, LocalIP.encode())
            .setHeader(X_GALEB_ZONE_ID, ZONE_ID).setBody("{\"router\":{\"group_id\":\"" + GROUP_ID
                    + "\",\"env\":\"" + ENVIRONMENT_NAME + "\",\"etag\":\"" + etag + "\"}}");
    asyncHttpClient.executeRequest(requestBuilder.build(), new AsyncCompletionHandler<String>() {
        @Override/* ww w .  j  a v  a 2 s .c  om*/
        public String onCompleted(Response response) throws Exception {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("post onCompleted done");
            }
            return "";
        }

        @Override
        public void onThrowable(Throwable t) {
            LOGGER.error(ExceptionUtils.getStackTrace(t));
        }
    });
}

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

License:Apache License

@Test
void testSignatureBaseStringWithProperlyEncodedUri() throws NoSuchAlgorithmException {

    List<Param> formParams = new ArrayList<>();
    formParams.add(new Param("c2", ""));
    formParams.add(new Param("a3", "2 q"));

    Request request = new RequestBuilder(HttpMethod.POST,
            Uri.create("http://example.com/request?b5=%3D%253D&a3=a&c%40=&a2=r%20b"))
                    .setBodyBuilder(new FormUrlEncodedRequestBodyBuilder(formParams)).build();

    testSignatureBaseString(request);// www  . j ava2 s  .  c o m
    testSignatureBaseStringWithEncodableOAuthToken(request);
}

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

License:Apache License

@Test
void testSignatureBaseStringWithRawUri() throws NoSuchAlgorithmException {
    // note: @ is legal so don't decode it into %40 because it won't be
    // encoded back
    // note: we don't know how to fix a = that should have been encoded as
    // %3D but who would be stupid enough to do that?

    List<Param> formParams = new ArrayList<>();
    formParams.add(new Param("c2", ""));
    formParams.add(new Param("a3", "2 q"));

    Request request = new RequestBuilder(HttpMethod.POST,
            Uri.create("http://example.com/request?b5=%3D%253D&a3=a&c%40=&a2=r b"))
                    .setBodyBuilder(new FormUrlEncodedRequestBodyBuilder(formParams)).build();

    testSignatureBaseString(request);//w  w w.  ja v a2s .  c  o  m
    testSignatureBaseStringWithEncodableOAuthToken(request);
}

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

License:Apache License

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

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

    final Request req = new RequestBuilder(HttpMethod.POST, Uri.create("http://photos.example.net/photos"))
            .setBodyBuilder(new FormUrlEncodedRequestBodyBuilder(postParams)).build();

    // From the signature tester, POST 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:
    // POST&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: wPkvxykrw+BTdCcGqKr+3I+PsiM=
    // 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="wPkvxykrw%2BBTdCcGqKr%2B3I%2BPsiM%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("wPkvxykrw+BTdCcGqKr+3I+PsiM=", sig);
}

From source file:io.gatling.http.client.BasicHttpTest.java

License:Apache License

@Test
void testPostWithHeadersAndFormParams() throws Throwable {
    withClient().run(client -> withServer(server).run(server -> {
        HttpHeaders h = new DefaultHttpHeaders();
        h.add(CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);

        List<Param> formParams = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            formParams.add(new Param("param_" + i, "value_" + i));
        }//from   w w  w . jav  a  2  s . com

        Request request = new RequestBuilder(HttpMethod.POST, Uri.create(getTargetUrl())).setHeaders(h)
                .setBodyBuilder(new FormUrlEncodedRequestBodyBuilder(formParams)).build();

        server.enqueueEcho();

        client.test(request, 0, new TestListener() {

            @Override
            public void onComplete0() {
                assertEquals(200, status.code());
                for (int i = 1; i < 5; i++) {
                    assertEquals(headers.get("X-param_" + i), "value_" + i);
                }
            }
        }).get(TIMEOUT_SECONDS, SECONDS);
    }));
}

From source file:io.gatling.http.client.FormMain.java

License:Apache License

public static void main(String[] args) throws Exception {
    try (GatlingHttpClient client = new GatlingHttpClient(new HttpClientConfig())) {

        List<Param> params = new ArrayList<>();
        params.add(new Param("firstname", "Mickey"));
        params.add(new Param("lastname", "Mouse"));

        Request request = new RequestBuilder(HttpMethod.POST,
                Uri.create("https://www.w3schools.com/action_page.php"))
                        .setBodyBuilder(new FormUrlEncodedRequestBodyBuilder(params))
                        .setNameResolver(client.getNameResolver()).setRequestTimeout(TIMEOUT_SECONDS * 1000)
                        .build();/*  w  w w. j a  va2 s. com*/

        final CountDownLatch latch1 = new CountDownLatch(1);
        client.execute(request, 0, true, new ResponseAsStringListener() {
            @Override
            public void onComplete() {
                LOGGER.debug(new DefaultResponse<>(status, headers, responseBody()).toString());
                latch1.countDown();
            }

            @Override
            public void onThrowable(Throwable e) {
                e.printStackTrace();
                latch1.countDown();
            }
        });
        latch1.await();
    }
}

From source file:io.jafka.http.HttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);/*from w w w .  j  ava 2s.  c  om*/
        }
        body = new ByteArrayOutputStream(64);
        args = new HashMap<String, String>(4);
        //
        if (request.getMethod() != HttpMethod.POST) {
            sendStatusMessage(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "POST METHOD REQUIRED");
            return;
        }
        HttpHeaders headers = request.headers();
        String contentType = headers.get("Content-Type");
        // ? text or octstream
        String key = headers.get("key");
        key = key != null ? key : headers.get("request_key");
        args.put("key", key);
        args.put("topic", headers.get("topic"));
        args.put("partition", headers.get("partition"));
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            //body.write(content.array());
            content.readBytes(body, content.readableBytes());
            //body.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //process request
            if (server.handler != null) {
                server.handler.handle(args, body.toByteArray());
            }
            if (!writeResponse(ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
            body = null;
            args = null;
        }
    }
}

From source file:io.jsync.http.impl.DefaultHttpServerRequest.java

License:Open Source License

@Override
public HttpServerRequest expectMultiPart(boolean expect) {
    if (expect) {
        String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType != null) {
            HttpMethod method = request.method();
            AsciiString lowerCaseContentType = new AsciiString(contentType.toLowerCase());
            boolean isURLEncoded = lowerCaseContentType
                    .startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
            if ((lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA) || isURLEncoded)
                    && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)
                            || method.equals(HttpMethod.PATCH))) {
                decoder = new HttpPostRequestDecoder(new DataFactory(), request);
            }//w  ww  .ja  va  2s  .  c  o  m
        }
    } else {
        decoder = null;
    }
    return this;
}

From source file:io.liveoak.container.protocols.http.HttpBinaryResourceRequestDecoderTest.java

License:Open Source License

@Test
public void testDecodePost() throws Exception {
    DefaultResourceRequest decoded = decode(HttpMethod.POST, "/memory/data", "Some text to be saved!");

    assertThat(decoded.requestType()).isEqualTo(RequestType.CREATE);

    assertThat(decoded.resourcePath().segments()).hasSize(2);
    assertThat(decoded.resourcePath().segments().get(0).name()).isEqualTo("memory");
    assertThat(decoded.resourcePath().segments().get(1).name()).isEqualTo("data");

    assertThat(decoded.state()).isNotNull();
    assertThat(decoded.state()).isInstanceOf(LazyResourceState.class);
    LazyResourceState state = (LazyResourceState) decoded.state();
    assertThat(state.contentAsByteBuf().toString(Charset.defaultCharset())).isEqualTo("Some text to be saved!");
}

From source file:io.liveoak.container.protocols.http.HttpResourceRequestDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, DefaultHttpRequest msg, List<Object> out) throws Exception {

    URI uri = new URI(msg.getUri());
    String query = uri.getRawQuery();
    if (query == null) {
        query = "?";
    } else {/*from w w w  .ja va2  s .c  o  m*/
        query = "?" + query;
    }

    QueryStringDecoder decoder = new QueryStringDecoder(query);

    String path = uri.getPath();

    int lastDotLoc = path.lastIndexOf('.');

    String extension = null;

    if (lastDotLoc > 0) {
        extension = path.substring(lastDotLoc + 1);
    }

    String acceptHeader = msg.headers().get(HttpHeaders.Names.ACCEPT);
    if (acceptHeader == null) {
        acceptHeader = "application/json";
    }
    MediaTypeMatcher mediaTypeMatcher = new DefaultMediaTypeMatcher(acceptHeader, extension);

    ResourceParams params = DefaultResourceParams.instance(decoder.parameters());

    // for cases when content is preset, and bypasses HttpRequestBodyHandler
    ByteBuf content = null;
    if (msg instanceof DefaultFullHttpRequest) {
        content = ((DefaultFullHttpRequest) msg).content().retain();
    }

    if (msg.getMethod().equals(HttpMethod.POST)) {
        String contentTypeHeader = msg.headers().get(HttpHeaders.Names.CONTENT_TYPE);
        MediaType contentType = new MediaType(contentTypeHeader);
        out.add(new DefaultResourceRequest.Builder(RequestType.CREATE, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.CONTENT_TYPE, contentType)
                .requestAttribute(HTTP_REQUEST, msg)
                .resourceState(new DefaultLazyResourceState(codecManager, contentType, content)).build());
    } else if (msg.getMethod().equals(HttpMethod.GET)) {
        out.add(new DefaultResourceRequest.Builder(RequestType.READ, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.ACCEPT, new MediaType(acceptHeader))
                .requestAttribute(HTTP_REQUEST, msg).pagination(decodePagination(params))
                .returnFields(decodeReturnFields(params)).sorting(decodeSorting(params)).build());
    } else if (msg.getMethod().equals(HttpMethod.PUT)) {
        String contentTypeHeader = msg.headers().get(HttpHeaders.Names.CONTENT_TYPE);
        MediaType contentType = new MediaType(contentTypeHeader);
        out.add(new DefaultResourceRequest.Builder(RequestType.UPDATE, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.CONTENT_TYPE, contentType)
                .requestAttribute(HTTP_REQUEST, msg)
                .resourceState(new DefaultLazyResourceState(codecManager, contentType, content)).build());
    } else if (msg.getMethod().equals(HttpMethod.DELETE)) {
        out.add(new DefaultResourceRequest.Builder(RequestType.DELETE, new ResourcePath(path))
                .resourceParams(params).mediaTypeMatcher(mediaTypeMatcher)
                .requestAttribute(HttpHeaders.Names.AUTHORIZATION,
                        msg.headers().get(HttpHeaders.Names.AUTHORIZATION))
                .requestAttribute(HttpHeaders.Names.ACCEPT, new MediaType(acceptHeader))
                .requestAttribute(HTTP_REQUEST, msg).build());
    }
}