Search in sources :

Example 36 with HttpPostRequestEncoder

use of io.netty.handler.codec.http.multipart.HttpPostRequestEncoder in project micronaut-core by micronaut-projects.

the class DefaultHttpClient method buildFormDataRequest.

private HttpPostRequestEncoder buildFormDataRequest(MutableHttpRequest clientHttpRequest, Object bodyValue) throws HttpPostRequestEncoder.ErrorDataEncoderException {
    HttpPostRequestEncoder postRequestEncoder = new HttpPostRequestEncoder(NettyHttpRequestBuilder.toHttpRequest(clientHttpRequest), false);
    Map<String, Object> formData;
    if (bodyValue instanceof Map) {
        formData = (Map<String, Object>) bodyValue;
    } else {
        formData = BeanMap.of(bodyValue);
    }
    for (Map.Entry<String, Object> entry : formData.entrySet()) {
        Object value = entry.getValue();
        if (value != null) {
            if (value instanceof Collection) {
                Collection collection = (Collection) value;
                for (Object val : collection) {
                    addBodyAttribute(postRequestEncoder, entry.getKey(), val);
                }
            } else {
                addBodyAttribute(postRequestEncoder, entry.getKey(), value);
            }
        }
    }
    return postRequestEncoder;
}
Also used : HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) ChannelPoolMap(io.netty.channel.pool.ChannelPoolMap) BeanMap(io.micronaut.core.beans.BeanMap) AbstractChannelPoolMap(io.netty.channel.pool.AbstractChannelPoolMap)

Example 37 with HttpPostRequestEncoder

use of io.netty.handler.codec.http.multipart.HttpPostRequestEncoder in project serve by pytorch.

the class ModelServerTest method testModelsInvokeMultipart.

@Test(alwaysRun = true, dependsOnMethods = { "testModelsInvokeJson" })
public void testModelsInvokeMultipart() throws InterruptedException, HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/models/noop/invoke");
    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, true);
    MemoryFileUpload body = new MemoryFileUpload("data", "test.txt", "text/plain", null, null, 4);
    body.setContent(Unpooled.copiedBuffer("test", StandardCharsets.UTF_8));
    encoder.addBodyHttpData(body);
    channel.writeAndFlush(encoder.finalizeRequest());
    if (encoder.isChunked()) {
        channel.writeAndFlush(encoder).sync();
    }
    TestUtils.getLatch().await();
    Assert.assertEquals(TestUtils.getResult(), "OK");
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Channel(io.netty.channel.Channel) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) MemoryFileUpload(io.netty.handler.codec.http.multipart.MemoryFileUpload) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.testng.annotations.Test)

Example 38 with HttpPostRequestEncoder

use of io.netty.handler.codec.http.multipart.HttpPostRequestEncoder in project mercury by yellow013.

the class HttpUploadClient method formpostmultipart.

/**
 * Multipart example
 */
private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(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
    // true =>
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true);
    // 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);
    }
    channel.flush();
    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();
    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder)

Example 39 with HttpPostRequestEncoder

use of io.netty.handler.codec.http.multipart.HttpPostRequestEncoder in project flink-mirror by flink-ci.

the class RestClient method createRequest.

private static Request createRequest(String targetAddress, String targetUrl, HttpMethod httpMethod, ByteBuf jsonPayload, Collection<FileUpload> fileUploads) throws IOException {
    if (fileUploads.isEmpty()) {
        HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, targetUrl, jsonPayload);
        httpRequest.headers().set(HttpHeaders.Names.HOST, targetAddress).set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE).add(HttpHeaders.Names.CONTENT_LENGTH, jsonPayload.capacity()).add(HttpHeaders.Names.CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);
        return new SimpleRequest(httpRequest);
    } else {
        HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, targetUrl);
        httpRequest.headers().set(HttpHeaders.Names.HOST, targetAddress).set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        // takes care of splitting the request into multiple parts
        HttpPostRequestEncoder bodyRequestEncoder;
        try {
            // we could use mixed attributes here but we have to ensure that the minimum size is
            // greater than
            // any file as the upload otherwise fails
            DefaultHttpDataFactory httpDataFactory = new DefaultHttpDataFactory(true);
            // the FileUploadHandler explicitly checks for multipart headers
            bodyRequestEncoder = new HttpPostRequestEncoder(httpDataFactory, httpRequest, true);
            Attribute requestAttribute = new MemoryAttribute(FileUploadHandler.HTTP_ATTRIBUTE_REQUEST);
            requestAttribute.setContent(jsonPayload);
            bodyRequestEncoder.addBodyHttpData(requestAttribute);
            int fileIndex = 0;
            for (FileUpload fileUpload : fileUploads) {
                Path path = fileUpload.getFile();
                if (Files.isDirectory(path)) {
                    throw new IllegalArgumentException("Upload of directories is not supported. Dir=" + path);
                }
                File file = path.toFile();
                LOG.trace("Adding file {} to request.", file);
                bodyRequestEncoder.addBodyFileUpload("file_" + fileIndex, file, fileUpload.getContentType(), false);
                fileIndex++;
            }
        } catch (HttpPostRequestEncoder.ErrorDataEncoderException e) {
            throw new IOException("Could not encode request.", e);
        }
        try {
            httpRequest = bodyRequestEncoder.finalizeRequest();
        } catch (HttpPostRequestEncoder.ErrorDataEncoderException e) {
            throw new IOException("Could not finalize request.", e);
        }
        return new MultipartRequest(httpRequest, bodyRequestEncoder);
    }
}
Also used : HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) Path(java.nio.file.Path) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) MemoryAttribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.MemoryAttribute) Attribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute) HttpPostRequestEncoder(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) IOException(java.io.IOException) MemoryAttribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.MemoryAttribute) DefaultHttpDataFactory(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) File(java.io.File)

Example 40 with HttpPostRequestEncoder

use of io.netty.handler.codec.http.multipart.HttpPostRequestEncoder in project netty by netty.

the class HttpUploadClient method formpostmultipart.

/**
 * Multipart example
 */
private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(SocketUtils.socketAddress(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 = // true => multipart
    new HttpPostRequestEncoder(factory, request, true);
    // 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);
    }
    channel.flush();
    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();
    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpPostRequestEncoder(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder)

Aggregations

HttpPostRequestEncoder (io.netty.handler.codec.http.multipart.HttpPostRequestEncoder)38 HttpRequest (io.netty.handler.codec.http.HttpRequest)20 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)16 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)13 DefaultHttpDataFactory (io.netty.handler.codec.http.multipart.DefaultHttpDataFactory)9 MemoryFileUpload (io.netty.handler.codec.http.multipart.MemoryFileUpload)9 Channel (io.netty.channel.Channel)8 ChannelFuture (io.netty.channel.ChannelFuture)8 HttpDataFactory (io.netty.handler.codec.http.multipart.HttpDataFactory)7 File (java.io.File)7 IOException (java.io.IOException)7 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)6 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)5 FileUpload (io.netty.handler.codec.http.multipart.FileUpload)5 InterfaceHttpData (io.netty.handler.codec.http.multipart.InterfaceHttpData)5 Test (org.junit.Test)5 ByteBuf (io.netty.buffer.ByteBuf)4 URISyntaxException (java.net.URISyntaxException)4 ByteBuffer (java.nio.ByteBuffer)4 ResponseParts (com.github.ambry.rest.NettyClient.ResponseParts)3