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.wso2.gw.emulator.Tester.java

License:Open Source License

private static void startHttpEmulator() {
    Emulator.getHttpEmulator().server()// w w  w  .  j a va  2  s . c  o m
            .given(configure().host("127.0.0.1").port(6065).writingDelay(4000).context("/user"))
            .when(request().withMethod(HttpMethod.POST).withBody("test"))
            .then(response().withBody("Test Response1").withStatusCode(HttpResponseStatus.OK)).operation()
            .start();
}

From source file:org.wso2.msf4j.internal.router.HttpServerTest.java

License:Open Source License

@Test
public void testConsumeXmlProduceXml() throws IOException, BeanConversionException {
    HttpURLConnection urlConn = request("/test/v1/textConsumeTextProduceXml", HttpMethod.POST);
    urlConn.setRequestProperty(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
    XmlBean xmlBean = new XmlBean();
    xmlBean.setName("send-something");
    xmlBean.setId(10);//from  w ww  . ja va 2 s  .c o  m
    xmlBean.setValue(15);
    writeContent(urlConn, (String) BeanConverter.instance("text/xml").toMedia(xmlBean));
    Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode());
    String respBody = getContent(urlConn);
    XmlBean xmlBean2 = (XmlBean) BeanConverter.instance("text/xml").toObject((String) respBody, XmlBean.class);
    Assert.assertEquals(xmlBean.getName(), xmlBean2.getName());
    Assert.assertEquals(xmlBean.getId(), xmlBean2.getId());
    Assert.assertEquals(xmlBean.getValue(), xmlBean2.getValue());
    urlConn.disconnect();
}

From source file:org.wso2.msf4j.security.oauth2.OAuth2SecurityInterceptor.java

License:Open Source License

/**
 * Validated the given accessToken with an external key server.
 *
 * @param accessToken AccessToken to be validated.
 * @return the response from the key manager server.
 *//*w  w  w. j  a v a  2 s.  co m*/
private String getValidatedTokenResponse(String accessToken) throws MSF4JSecurityException {
    URL url;
    try {
        url = new URL(AUTH_SERVER_URL);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(HttpMethod.POST.name());
        urlConn.getOutputStream().write(("token=" + accessToken).getBytes(Charsets.UTF_8));
        return new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
    } catch (java.io.IOException e) {
        log.error("Error invoking Authorization Server", e);
        throw new MSF4JSecurityException(SecurityErrorCode.GENERIC_ERROR, "Error invoking Authorization Server",
                e);
    }
}

From source file:org.wso2.siddhi.extension.input.transport.http.Util.ServerUtil.java

License:Open Source License

public static HttpURLConnection request(URI baseURI, String path, String method, boolean keepAlive)
        throws IOException {
    URL url = baseURI.resolve(path).toURL();
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    if (method.equals(HttpMethod.POST.name()) || method.equals(HttpMethod.PUT.name())) {
        urlConn.setDoOutput(true);/*from w  ww.  j  a va 2 s .c  o m*/
    }
    urlConn.setRequestMethod(method);
    if (!keepAlive) {
        urlConn.setRequestProperty("Connection", "Keep-Alive");
    }
    return urlConn;
}

From source file:reactor.ipc.netty.http.client.HttpClient.java

License:Open Source License

/**
 * HTTP POST the passed URL. When connection has been made, the passed handler is
 * invoked and can be used to build precisely the request and write data to it.
 *
 * @param url the target remote URL//from w  w w  .  j a v a 2  s. co  m
 * @param handler the {@link Function} to invoke on open channel
 *
 * @return a {@link Mono} of the {@link HttpServerResponse} ready to consume for
 * response
 */
public final Mono<HttpClientResponse> post(String url,
        Function<? super HttpClientRequest, ? extends Publisher<Void>> handler) {
    return request(HttpMethod.POST, url, handler);
}

From source file:reactor.ipc.netty.http.client.HttpClientFormEncoder.java

License:Open Source License

/**
 * @param factory the factory used to create InterfaceHttpData
 * @param request the request to encode/*from   ww w . jav a  2  s .  co  m*/
 * @param multipart True if the FORM is a ENCTYPE="multipart/form-data"
 * @param charset the charset to use as default
 * @param encoderMode the mode for the encoder to use. See {@link EncoderMode} for the
 * details.
 *
 * @throws NullPointerException      for request or charset or factory
 * @throws ErrorDataEncoderException if the request is not a POST
 */
HttpClientFormEncoder(HttpDataFactory factory, HttpRequest request, boolean multipart, Charset charset,
        EncoderMode encoderMode) throws ErrorDataEncoderException {
    if (factory == null) {
        throw new NullPointerException("factory");
    }
    if (request == null) {
        throw new NullPointerException("request");
    }
    if (charset == null) {
        throw new NullPointerException("charset");
    }
    HttpMethod method = request.method();
    if (!(method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)
            || method.equals(HttpMethod.OPTIONS))) {
        throw new ErrorDataEncoderException("Cannot create a Encoder if not a POST");
    }
    this.request = request;
    this.charset = charset;
    this.newCharset = charset;
    this.factory = factory;
    this.progressFlux = DirectProcessor.create();
    this.cleanOnTerminate = true;
    this.newMode = encoderMode;
    this.newMultipart = multipart;

    // Fill default values
    bodyListDatas = new ArrayList<>();
    // default mode
    isLastChunk = false;
    isLastChunkSent = false;
    isMultipart = multipart;
    multipartHttpDatas = new ArrayList<>();
    this.encoderMode = encoderMode;
    if (isMultipart) {
        initDataMultipart();
    }
}

From source file:reactor.ipc.netty.http.server.HttpPredicate.java

License:Open Source License

/**
 * An alias for {@link HttpPredicate#http}.
 * <p>//from w w  w.ja v  a  2 s. c om
 * Creates a {@link Predicate} based on a URI template filtering .
 * <p>
 * This will listen for POST Method.
 *
 * @param uri The string to compile into a URI template and use for matching
 *
 * @return The new {@link Predicate}.
 *
 * @see Predicate
 */
public static Predicate<HttpServerRequest> post(String uri) {
    return http(uri, null, HttpMethod.POST);
}

From source file:test.httpupload.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *//*from ww  w .j  a  v  a 2s. c  om*/
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart

    // 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
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder).sync();
    }

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}

From source file:test.httpupload.HttpUploadClient.java

License:Apache License

/**
 * Multipart example//  w  w  w .  j  a va 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 {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // 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()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder).sync();
    }

    // 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:uapi.web.http.netty.internal.NettyHttpRequest.java

License:Open Source License

NettyHttpRequest(final ILogger logger, final HttpRequest httpRequest) {
    this._logger = logger;
    this._request = httpRequest;

    HttpHeaders headers = this._request.headers();
    Looper.from(headers.iteratorAsString())
            .foreach(entry -> this._headers.put(entry.getKey().toLowerCase(), entry.getValue()));

    this._uri = this._request.uri();
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this._uri);
    Map<String, List<String>> params = queryStringDecoder.parameters();
    Looper.from(params.entrySet()).foreach(entry -> this._params.put(entry.getKey(), entry.getValue()));

    HttpVersion version = this._request.protocolVersion();
    if (HttpVersion.HTTP_1_0.equals(version)) {
        this._version = uapi.web.http.HttpVersion.V_1_0;
    } else if (HttpVersion.HTTP_1_1.equals(version)) {
        this._version = uapi.web.http.HttpVersion.V_1_1;
    } else {/*from  ww  w.ja  v a 2 s.  c  om*/
        throw new KernelException("Unsupported Http version - {}", version);
    }

    HttpMethod method = this._request.method();
    if (HttpMethod.GET.equals(method)) {
        this._method = uapi.web.http.HttpMethod.GET;
    } else if (HttpMethod.PUT.equals(method)) {
        this._method = uapi.web.http.HttpMethod.PUT;
    } else if (HttpMethod.POST.equals(method)) {
        this._method = uapi.web.http.HttpMethod.POST;
    } else if (HttpMethod.PATCH.equals(method)) {
        this._method = uapi.web.http.HttpMethod.PATCH;
    } else if (HttpMethod.DELETE.equals(method)) {
        this._method = uapi.web.http.HttpMethod.DELETE;
    } else {
        throw new KernelException("Unsupported http method {}", method.toString());
    }

    // Decode content type
    String contentTypeString = this._headers.get(HttpHeaderNames.CONTENT_TYPE.toString());
    if (contentTypeString == null) {
        this._conentType = ContentType.TEXT;
        this._charset = Charset.forName("UTF-8");
    } else {
        String[] contentTypeInfo = contentTypeString.split(";");
        if (contentTypeInfo.length < 0) {
            this._conentType = ContentType.TEXT;
            this._charset = CharsetUtil.UTF_8;
        } else if (contentTypeInfo.length == 1) {
            this._conentType = ContentType.parse(contentTypeInfo[0].trim());
            this._charset = CharsetUtil.UTF_8;
        } else {
            this._conentType = ContentType.parse(contentTypeInfo[0].trim());
            this._charset = Looper.from(contentTypeInfo).map(info -> info.split("="))
                    .filter(kv -> kv.length == 2).filter(kv -> kv[0].trim().equalsIgnoreCase("charset"))
                    .map(kv -> kv[1].trim()).map(Charset::forName).first(CharsetUtil.UTF_8);
        }
    }
}