List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestEncoder finalizeRequest
public HttpRequest finalizeRequest() throws ErrorDataEncoderException
From source file:dpfmanager.shell.modules.client.upload.HttpClient.java
License:Open Source License
/** * Multipart POST//from w w w . j av a2 s. com */ private void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory) throws Exception { // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); 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); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); // Add the files int i = 0; for (File file : files) { bodyRequestEncoder.addBodyFileUpload("file" + i, file, "image/tiff", false); i++; } for (File file : tmpFiles) { bodyRequestEncoder.addBodyFileUpload("file" + i, file, "image/tiff", false); i++; } // Add configuration if (config != null) { bodyRequestEncoder.addBodyFileUpload("config", config, "application/octet-stream", false); } // Add job id if (id != null) { bodyRequestEncoder.addBodyAttribute("id", id); } // 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(); }
From source file:io.example.UploadClient.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 av a 2 s . 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.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); } System.out.println("Sent formpost"); 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:io.example.UploadClient.HttpUploadClient.java
License:Apache License
/** * Multipart example// w w w . j ava 2 s . c om */ 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); } System.out.println("Sent formpostmultipart"); 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(); }
From source file:io.vertx.ext.web.client.impl.HttpRequestImpl.java
License:Open Source License
private void send(String contentType, Object body, Handler<AsyncResult<HttpResponse<T>>> handler) { Future<HttpClientResponse> responseFuture = Future.<HttpClientResponse>future().setHandler(ar -> { if (ar.succeeded()) { HttpClientResponse resp = ar.result(); Future<HttpResponse<T>> fut = Future.future(); fut.setHandler(handler);// w w w .j a v a 2s. c o m resp.exceptionHandler(err -> { if (!fut.isComplete()) { fut.fail(err); } }); resp.pause(); codec.create(ar2 -> { resp.resume(); if (ar2.succeeded()) { BodyStream<T> stream = ar2.result(); stream.exceptionHandler(err -> { if (!fut.isComplete()) { fut.fail(err); } }); resp.endHandler(v -> { if (!fut.isComplete()) { stream.end(); if (stream.result().succeeded()) { fut.complete(new HttpResponseImpl<>(resp, null, stream.result().result())); } else { fut.fail(stream.result().cause()); } } }); Pump responsePump = Pump.pump(resp, stream); responsePump.start(); } else { handler.handle(Future.failedFuture(ar2.cause())); } }); } else { handler.handle(Future.failedFuture(ar.cause())); } }); HttpClientRequest req; String requestURI; if (params != null && params.size() > 0) { QueryStringEncoder enc = new QueryStringEncoder(uri); params.forEach(param -> { enc.addParam(param.getKey(), param.getValue()); }); requestURI = enc.toString(); } else { requestURI = uri; } if (ssl != options.isSsl()) { req = client.request(method, new RequestOptions().setSsl(ssl).setHost(host).setPort(port).setURI(requestURI)); } else { req = client.request(method, port, host, requestURI); } req.setFollowRedirects(followRedirects); if (headers != null) { req.headers().addAll(headers); } req.exceptionHandler(err -> { if (!responseFuture.isComplete()) { responseFuture.fail(err); } }); req.handler(resp -> { if (!responseFuture.isComplete()) { responseFuture.complete(resp); } }); if (timeout > 0) { req.setTimeout(timeout); } if (body != null) { if (contentType != null) { String prev = req.headers().get(HttpHeaders.CONTENT_TYPE); if (prev == null) { req.putHeader(HttpHeaders.CONTENT_TYPE, contentType); } else { contentType = prev; } } if (body instanceof ReadStream<?>) { ReadStream<Buffer> stream = (ReadStream<Buffer>) body; if (headers == null || !headers.contains(HttpHeaders.CONTENT_LENGTH)) { req.setChunked(true); } Pump pump = Pump.pump(stream, req); stream.exceptionHandler(err -> { req.reset(); if (!responseFuture.isComplete()) { responseFuture.fail(err); } }); stream.endHandler(v -> { pump.stop(); req.end(); }); pump.start(); } else { Buffer buffer; if (body instanceof Buffer) { buffer = (Buffer) body; } else if (body instanceof MultiMap) { try { MultiMap attributes = (MultiMap) body; boolean multipart = "multipart/form-data".equals(contentType); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.POST, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, multipart); for (Map.Entry<String, String> attribute : attributes) { encoder.addBodyAttribute(attribute.getKey(), attribute.getValue()); } encoder.finalizeRequest(); for (String headerName : request.headers().names()) { req.putHeader(headerName, request.headers().get(headerName)); } if (encoder.isChunked()) { buffer = Buffer.buffer(); while (true) { HttpContent chunk = encoder.readChunk(new UnpooledByteBufAllocator(false)); ByteBuf content = chunk.content(); if (content.readableBytes() == 0) { break; } buffer.appendBuffer(Buffer.buffer(content)); } } else { ByteBuf content = request.content(); buffer = Buffer.buffer(content); } } catch (Exception e) { throw new VertxException(e); } } else if (body instanceof JsonObject) { buffer = Buffer.buffer(((JsonObject) body).encode()); } else { buffer = Buffer.buffer(Json.encode(body)); } req.end(buffer); } } else { req.end(); } }
From source file:io.vertx.webclient.impl.HttpRequestImpl.java
License:Open Source License
private <R> void send(String contentType, Object body, BodyCodec<R> codec, Handler<AsyncResult<HttpResponse<R>>> handler) { Future<HttpClientResponse> responseFuture = Future.<HttpClientResponse>future().setHandler(ar -> { if (ar.succeeded()) { HttpClientResponse resp = ar.result(); Future<HttpResponse<R>> fut = Future.future(); fut.setHandler(handler);//from w ww .j a v a 2 s.c om resp.exceptionHandler(err -> { if (!fut.isComplete()) { fut.fail(err); } }); resp.pause(); codec.create(ar2 -> { resp.resume(); if (ar2.succeeded()) { BodyStream<R> stream = ar2.result(); stream.exceptionHandler(err -> { if (!fut.isComplete()) { fut.fail(err); } }); resp.endHandler(v -> { if (!fut.isComplete()) { stream.end(); if (stream.result().succeeded()) { fut.complete(new HttpResponseImpl<>(resp, null, stream.result().result())); } else { fut.fail(stream.result().cause()); } } }); Pump responsePump = Pump.pump(resp, stream); responsePump.start(); } else { handler.handle(Future.failedFuture(ar2.cause())); } }); } else { handler.handle(Future.failedFuture(ar.cause())); } }); HttpClientRequest req; String requestURI; if (params != null && params.size() > 0) { QueryStringEncoder enc = new QueryStringEncoder(uri); params.forEach(param -> { enc.addParam(param.getKey(), param.getValue()); }); requestURI = enc.toString(); } else { requestURI = uri; } if (port != -1) { if (host != null) { req = client.request(method, port, host, requestURI); } else { throw new IllegalStateException("Both host and port must be set with an explicit port"); } } else { if (host != null) { req = client.request(method, host, requestURI); } else { req = client.request(method, requestURI); } } if (headers != null) { req.headers().addAll(headers); } req.exceptionHandler(err -> { if (!responseFuture.isComplete()) { responseFuture.fail(err); } }); req.handler(resp -> { if (!responseFuture.isComplete()) { responseFuture.complete(resp); } }); if (timeout > 0) { req.setTimeout(timeout); } if (body != null) { if (contentType != null) { String prev = req.headers().get(HttpHeaders.CONTENT_TYPE); if (prev == null) { req.putHeader(HttpHeaders.CONTENT_TYPE, contentType); } else { contentType = prev; } } if (body instanceof ReadStream<?>) { ReadStream<Buffer> stream = (ReadStream<Buffer>) body; if (headers == null || !headers.contains(HttpHeaders.CONTENT_LENGTH)) { req.setChunked(true); } Pump pump = Pump.pump(stream, req); stream.exceptionHandler(err -> { req.reset(); if (!responseFuture.isComplete()) { responseFuture.fail(err); } }); stream.endHandler(v -> { pump.stop(); req.end(); }); pump.start(); } else { Buffer buffer; if (body instanceof Buffer) { buffer = (Buffer) body; } else if (body instanceof MultiMap) { try { MultiMap attributes = (MultiMap) body; boolean multipart = "multipart/form-data".equals(contentType); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.POST, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, multipart); for (Map.Entry<String, String> attribute : attributes) { encoder.addBodyAttribute(attribute.getKey(), attribute.getValue()); } encoder.finalizeRequest(); for (String headerName : request.headers().names()) { req.putHeader(headerName, request.headers().get(headerName)); } if (encoder.isChunked()) { buffer = Buffer.buffer(); while (true) { HttpContent chunk = encoder.readChunk(new UnpooledByteBufAllocator(false)); ByteBuf content = chunk.content(); if (content.readableBytes() == 0) { break; } buffer.appendBuffer(Buffer.buffer(content)); } } else { ByteBuf content = request.content(); buffer = Buffer.buffer(content); } } catch (Exception e) { throw new VertxException(e); } } else if (body instanceof JsonObject) { buffer = Buffer.buffer(((JsonObject) body).encode()); } else { buffer = Buffer.buffer(Json.encode(body)); } req.end(buffer); } } else { req.end(); } }
From source file:org.ballerinalang.stdlib.utils.MultipartUtils.java
License:Open Source License
/** * Prepare carbon request message with multiparts. * * @param outboundRequest Represent outbound carbon request * @param requestStruct Ballerina request struct which contains multipart data *//*from w w w . j a va 2 s.c om*/ private static void prepareRequestWithMultiparts(HttpCarbonMessage outboundRequest, BMap<String, BValue> requestStruct) { BMap<String, BValue> entityStruct = requestStruct.get(REQUEST_ENTITY_FIELD) != null ? (BMap<String, BValue>) requestStruct.get(REQUEST_ENTITY_FIELD) : null; if (entityStruct != null) { BValueArray bodyParts = entityStruct.getNativeData(BODY_PARTS) != null ? (BValueArray) entityStruct.getNativeData(BODY_PARTS) : null; if (bodyParts != null) { HttpDataFactory dataFactory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); setDataFactory(dataFactory); try { HttpPostRequestEncoder nettyEncoder = new HttpPostRequestEncoder(dataFactory, outboundRequest.getNettyHttpRequest(), true); for (int i = 0; i < bodyParts.size(); i++) { BMap<String, BValue> bodyPart = (BMap<String, BValue>) bodyParts.getRefValue(i); encodeBodyPart(nettyEncoder, outboundRequest.getNettyHttpRequest(), bodyPart); } nettyEncoder.finalizeRequest(); requestStruct.addNativeData(MULTIPART_ENCODER, nettyEncoder); } catch (HttpPostRequestEncoder.ErrorDataEncoderException e) { LOG.error("Error occurred while creating netty request encoder for multipart data binding", e.getMessage()); } } } }
From source file:org.ballerinalang.test.mime.Util.java
License:Open Source License
/** * Prepare carbon request message with multiparts. * * @param outboundRequest Represent outbound carbon request * @param requestStruct Ballerina request struct which contains multipart data *///from w ww. j ava2s. co m private static void prepareRequestWithMultiparts(HttpCarbonMessage outboundRequest, BMap<String, BValue> requestStruct) { BMap<String, BValue> entityStruct = requestStruct.get(REQUEST_ENTITY_FIELD) != null ? (BMap<String, BValue>) requestStruct.get(REQUEST_ENTITY_FIELD) : null; if (entityStruct != null) { BRefValueArray bodyParts = entityStruct.getNativeData(BODY_PARTS) != null ? (BRefValueArray) entityStruct.getNativeData(BODY_PARTS) : null; if (bodyParts != null) { HttpDataFactory dataFactory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); setDataFactory(dataFactory); try { HttpPostRequestEncoder nettyEncoder = new HttpPostRequestEncoder(dataFactory, outboundRequest.getNettyHttpRequest(), true); for (int i = 0; i < bodyParts.size(); i++) { BMap<String, BValue> bodyPart = (BMap<String, BValue>) bodyParts.get(i); encodeBodyPart(nettyEncoder, outboundRequest.getNettyHttpRequest(), bodyPart); } nettyEncoder.finalizeRequest(); requestStruct.addNativeData(MULTIPART_ENCODER, nettyEncoder); } catch (HttpPostRequestEncoder.ErrorDataEncoderException e) { log.error("Error occurred while creating netty request encoder for multipart data binding", e.getMessage()); } } } }
From source file:org.server.core.netty.http.NHttpRequestParams.java
License:Apache License
/** * ?//from w w w. java 2 s .co m * * @return * @throws ErrorDataEncoderException * post ? */ Object[] getFormObject(HttpRequest request) throws ErrorDataEncoderException { boolean formNoneEntity = form == null || form.isEmpty(); boolean uploadFileNoneEntity = uploadFormFile == null || uploadFormFile.isEmpty(); if (formNoneEntity && uploadFileNoneEntity) return null; HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(inMemoryFactory, request, multipart); if (!formNoneEntity) { for (Entry<String, String> item : form.entrySet()) { encoder.addBodyAttribute(item.getKey(), item.getValue()); } } if (!uploadFileNoneEntity) { for (Entry<String, File> item : uploadFormFile.entrySet()) { encoder.addBodyFileUpload(item.getKey(), item.getValue(), headers != null ? headers.get(HttpHeaders.Names.CONTENT_TYPE) : null, false); } } return new Object[] { encoder.finalizeRequest(), encoder }; }
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 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(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//from ww w. j a v a 2s .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(); }