Example usage for io.netty.handler.codec.http.multipart HttpPostRequestEncoder addBodyAttribute

List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestEncoder addBodyAttribute

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.multipart HttpPostRequestEncoder addBodyAttribute.

Prototype

public void addBodyAttribute(String name, String value) throws ErrorDataEncoderException 

Source Link

Document

Add a simple attribute in the body as Name=Value

Usage

From source file: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
 */// w w w  .j a v a2s.c o m
private static List<InterfaceHttpData> formPost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {

    // Start the connection attempt
    Channel channel = bootstrap.connect(host, port).sync().channel();

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

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false not multipart
    } catch (NullPointerException e) {
        // should not be since args are not null
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // test if getMethod is a POST getMethod
        e.printStackTrace();
    }

    // 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
    try {
        bodyRequestEncoder.addBodyAttribute("getform", "POST");
        bodyRequestEncoder.addBodyAttribute("info", "first value");
        bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
        bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
        bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
        bodyRequestEncoder.addBodyAttribute("Send", "Send");
    } catch (NullPointerException e) {
        // should not be since not null args
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // finalize request
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // 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).awaitUninterruptibly();
    }

    // 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:ccwihr.client.t1.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory
 * management)//from w ww  . j a v a2 s .com
 * @param se12 
 *
 * @return the list of HttpData object (attribute and file) to be reused on
 *         next post
 */
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        SyncEntity se12, 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

    // 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);
    }
    channel.flush();

    // 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:cn.wcl.test.netty.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
 *///ww  w.  j  ava  2 s .com
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);
    }
    channel.flush();

    // 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:com.cmz.http.upload.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 w  w w.j  a va 2  s  .  co m
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(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,
            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);
    }
    channel.flush();

    // 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:com.digisky.innerproxy.testclient.HttpSnoopClient.java

License:Apache License

public static void test(Channel ch, String uri, String sjson) {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.setMethod(HttpMethod.POST);//from w  ww .j  a  v  a2s  .com
    request.setUri("/" + uri);
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(request, false);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // false => not multipart
      //***********************************************************************
    try {
        bodyRequestEncoder.addBodyAttribute("val", sjson);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //***********************************************************************
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ch.writeAndFlush(request);
    try {
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.digisky.outerproxy.testclient.HttpSnoopClient.java

License:Apache License

public static void testWithEncode(Channel ch, String uri, String sjson) {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    request.setMethod(HttpMethod.POST);/*from ww w  . j  a  v a2s.  c o m*/
    request.setUri("/" + uri);
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(request, false);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // false => not multipart
      //***********************************************************************
    ByteBuf b = Unpooled.buffer();
    b.writeBytes("{}".getBytes());
    try {
        bodyRequestEncoder.addBodyAttribute("val", sjson);
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //***********************************************************************
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ch.writeAndFlush(request);
    try {
        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.github.ambry.rest.NettyMultipartRequestTest.java

License:Open Source License

/**
 * Tests different scenarios with {@link NettyMultipartRequest#prepare()}.
 * Currently tests://from   w ww .  j av  a  2  s .  co m
 * 1. Idempotency of {@link NettyMultipartRequest#prepare()}.
 * 2. Exception scenarios of {@link NettyMultipartRequest#prepare()}.
 * @throws Exception
 */
@Test
public void prepareTest() throws Exception {
    // prepare half baked data
    HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    HttpPostRequestEncoder encoder = createEncoder(httpRequest, null);
    NettyMultipartRequest request = new NettyMultipartRequest(encoder.finalizeRequest(), nettyMetrics);
    assertTrue("Request channel is not open", request.isOpen());
    // insert random data
    HttpContent httpContent = new DefaultHttpContent(Unpooled.wrappedBuffer(RestTestUtils.getRandomBytes(10)));
    request.addContent(httpContent);
    // prepare should fail
    try {
        request.prepare();
        fail("Preparing request should have failed");
    } catch (HttpPostRequestDecoder.NotEnoughDataDecoderException e) {
        assertEquals("Reference count is not as expected", 1, httpContent.refCnt());
    } finally {
        closeRequestAndValidate(request);
    }

    // more than one blob part
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(RestUtils.Headers.BLOB_SIZE, 256);
    InMemoryFile[] files = new InMemoryFile[2];
    files[0] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    files[1] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    request = createRequest(httpHeaders, files);
    assertEquals("Request size does not match", 256, request.getSize());
    try {
        request.prepare();
        fail("Prepare should have failed because there was more than one " + RestUtils.MultipartPost.BLOB_PART);
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.MalformedRequest,
                e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }

    // more than one part named "part-1"
    files = new InMemoryFile[2];
    files[0] = new InMemoryFile("Part-1", ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    files[1] = new InMemoryFile("Part-1", ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    request = createRequest(null, files);
    try {
        request.prepare();
        fail("Prepare should have failed because there was more than one part named Part-1");
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.MalformedRequest,
                e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }

    // size of blob does not match the advertized size
    httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(RestUtils.Headers.BLOB_SIZE, 256);
    files = new InMemoryFile[1];
    files[0] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(128)));
    request = createRequest(httpHeaders, files);
    try {
        request.prepare();
        fail("Prepare should have failed because there was more than one " + RestUtils.MultipartPost.BLOB_PART);
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.BadRequest, e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }

    // non fileupload (file attribute present)
    httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    HttpHeaders.setHeader(httpRequest, RestUtils.Headers.BLOB_SIZE, 256);
    files = new InMemoryFile[1];
    files[0] = new InMemoryFile(RestUtils.MultipartPost.BLOB_PART,
            ByteBuffer.wrap(RestTestUtils.getRandomBytes(256)));
    encoder = createEncoder(httpRequest, files);
    encoder.addBodyAttribute("dummyKey", "dummyValue");
    request = new NettyMultipartRequest(encoder.finalizeRequest(), nettyMetrics);
    assertTrue("Request channel is not open", request.isOpen());
    while (!encoder.isEndOfInput()) {
        // Sending null for ctx because the encoder is OK with that.
        request.addContent(encoder.readChunk(null));
    }
    try {
        request.prepare();
        fail("Prepare should have failed because there was non fileupload");
    } catch (RestServiceException e) {
        assertEquals("Unexpected RestServiceErrorCode", RestServiceErrorCode.BadRequest, e.getErrorCode());
    } finally {
        closeRequestAndValidate(request);
    }
}

From source file:com.netty.file.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 .  ja  va 2s.c  o  m
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.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);
    }
    channel.flush();

    // 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:com.topsec.bdc.platform.api.test.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 * /*from  ww w  . j av a2 s  .c o m*/
 * @return the list of HttpData object (attribute and file) to be reused on next post
 */
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);
    }
    channel.flush();

    // 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:de.ocarthon.core.network.HttpClient.java

License:Apache License

public synchronized String postRequest(String query, List<Map.Entry<String, String>> postParameters,
        String filePostName, String fileName, ByteBuf fileData, String mime) {
    if (bootstrap == null) {
        setupBootstrap();/*  ww  w.ja v  a  2 s . com*/
    }

    if (channel == null || forceReconnect) {
        ChannelFuture cf = bootstrap.connect(host, port);
        forceReconnect = false;
        cf.awaitUninterruptibly();
        channel = cf.channel();

        channel.pipeline().addLast("handler", new SimpleChannelInboundHandler<HttpObject>() {
            @Override
            protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                if (msg instanceof HttpResponse) {
                    HttpResponse response = ((HttpResponse) msg);
                    String connection = (String) response.headers().get(HttpHeaderNames.CONNECTION);
                    if (connection != null && connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString()))
                        forceReconnect = true;
                }

                if (msg instanceof HttpContent) {
                    HttpContent chunk = (HttpContent) msg;
                    String message = chunk.content().toString(CharsetUtil.UTF_8);

                    if (!message.isEmpty()) {
                        result[0] = message;

                        synchronized (result) {
                            result.notify();
                        }
                    }
                }
            }
        });
    }
    boolean isFileAttached = fileData != null && fileData.isReadable();
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            scheme + "://" + host + ":" + port + "/" + query);
    HttpPostRequestEncoder bodyReqEncoder;
    try {
        bodyReqEncoder = new HttpPostRequestEncoder(httpDataFactory, request, isFileAttached);

        for (Map.Entry<String, String> entry : postParameters) {
            bodyReqEncoder.addBodyAttribute(entry.getKey(), entry.getValue());
        }

        if (isFileAttached) {
            if (mime == null)
                mime = "application/octet-stream";

            MixedFileUpload mfu = new MixedFileUpload(filePostName, fileName, mime, "binary", null,
                    fileData.capacity(), DefaultHttpDataFactory.MINSIZE);
            mfu.addContent(fileData, true);
            bodyReqEncoder.addBodyHttpData(mfu);
        }

        HttpHeaders headers = request.headers();
        headers.set(HttpHeaderNames.HOST, host);
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
        headers.set(HttpHeaderNames.USER_AGENT, "OcarthonCore HttpClient");
        request = bodyReqEncoder.finalizeRequest();
    } catch (Exception e) {
        throw new NullPointerException("key or value is empty or null");
    }

    channel.write(request);

    if (bodyReqEncoder.isChunked()) {
        channel.write(bodyReqEncoder);
    }
    channel.flush();

    synchronized (result) {
        try {
            result.wait();
        } catch (InterruptedException e) {
            return null;
        }
    }

    return result[0];
}