use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.
the class NettyRequestFactory method body.
private NettyBody body(Request request, boolean connect) {
NettyBody nettyBody = null;
if (!connect) {
Charset bodyCharset = withDefault(request.getCharset(), DEFAULT_CHARSET);
if (request.getByteData() != null) {
nettyBody = new NettyByteArrayBody(request.getByteData());
} else if (request.getCompositeByteData() != null) {
nettyBody = new NettyCompositeByteArrayBody(request.getCompositeByteData());
} else if (request.getStringData() != null) {
nettyBody = new NettyByteBufferBody(StringUtils.charSequence2ByteBuffer(request.getStringData(), bodyCharset));
} else if (request.getByteBufferData() != null) {
nettyBody = new NettyByteBufferBody(request.getByteBufferData());
} else if (request.getStreamData() != null) {
nettyBody = new NettyInputStreamBody(request.getStreamData());
} else if (isNonEmpty(request.getFormParams())) {
CharSequence contentType = null;
if (!request.getHeaders().contains(CONTENT_TYPE)) {
contentType = HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED;
}
nettyBody = new NettyByteBufferBody(urlEncodeFormParams(request.getFormParams(), bodyCharset), contentType);
} else if (isNonEmpty(request.getBodyParts())) {
nettyBody = new NettyMultipartBody(request.getBodyParts(), request.getHeaders(), config);
} else if (request.getFile() != null) {
nettyBody = new NettyFileBody(request.getFile(), config);
} else if (request.getBodyGenerator() instanceof FileBodyGenerator) {
FileBodyGenerator fileBodyGenerator = (FileBodyGenerator) request.getBodyGenerator();
nettyBody = new NettyFileBody(fileBodyGenerator.getFile(), fileBodyGenerator.getRegionSeek(), fileBodyGenerator.getRegionLength(), config);
} else if (request.getBodyGenerator() instanceof InputStreamBodyGenerator) {
InputStreamBodyGenerator inStreamGenerator = InputStreamBodyGenerator.class.cast(request.getBodyGenerator());
nettyBody = new NettyInputStreamBody(inStreamGenerator.getInputStream(), inStreamGenerator.getContentLength());
} else if (request.getBodyGenerator() instanceof ReactiveStreamsBodyGenerator) {
ReactiveStreamsBodyGenerator reactiveStreamsBodyGenerator = (ReactiveStreamsBodyGenerator) request.getBodyGenerator();
nettyBody = new NettyReactiveStreamsBody(reactiveStreamsBodyGenerator.getPublisher(), reactiveStreamsBodyGenerator.getContentLength());
} else if (request.getBodyGenerator() != null) {
nettyBody = new NettyBodyBody(request.getBodyGenerator().createBody(), config);
}
}
return nettyBody;
}
use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project camel by apache.
the class DefaultAhcBinding method populateBody.
protected void populateBody(RequestBuilder builder, AhcEndpoint endpoint, Exchange exchange) throws CamelExchangeException {
Message in = exchange.getIn();
if (in.getBody() == null) {
return;
}
String contentType = ExchangeHelper.getContentType(exchange);
BodyGenerator body = in.getBody(BodyGenerator.class);
String charset = IOHelper.getCharsetName(exchange, false);
if (body == null) {
try {
Object data = in.getBody();
if (data != null) {
if (contentType != null && AhcConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (!endpoint.getComponent().isAllowJavaSerializedObject()) {
throw new CamelExchangeException("Content-type " + AhcConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
}
// serialized java object
Serializable obj = in.getMandatoryBody(Serializable.class);
// write object to output stream
ByteArrayOutputStream bos = new ByteArrayOutputStream(endpoint.getBufferSize());
AhcHelper.writeObjectToStream(bos, obj);
byte[] bytes = bos.toByteArray();
body = new ByteArrayBodyGenerator(bytes);
IOHelper.close(bos);
} else if (data instanceof File || data instanceof GenericFile) {
// file based (could potentially also be a FTP file etc)
File file = in.getBody(File.class);
if (file != null) {
body = new FileBodyGenerator(file);
}
} else if (data instanceof String) {
// (for example application/x-www-form-urlencoded forms being sent)
if (charset != null) {
body = new ByteArrayBodyGenerator(((String) data).getBytes(charset));
} else {
body = new ByteArrayBodyGenerator(((String) data).getBytes());
}
}
// fallback as input stream
if (body == null) {
// force the body as an input stream since this is the fallback
InputStream is = in.getMandatoryBody(InputStream.class);
body = new InputStreamBodyGenerator(is);
}
}
} catch (UnsupportedEncodingException e) {
throw new CamelExchangeException("Error creating BodyGenerator from message body", exchange, e);
} catch (IOException e) {
throw new CamelExchangeException("Error serializing message body", exchange, e);
}
}
if (body != null) {
log.trace("Setting body {}", body);
builder.setBody(body);
}
if (charset != null) {
log.trace("Setting body charset {}", charset);
builder.setCharset(Charset.forName(charset));
}
// must set content type, even if its null, otherwise it may default to
// application/x-www-form-urlencoded which may not be your intention
log.trace("Setting Content-Type {}", contentType);
if (ObjectHelper.isNotEmpty(contentType)) {
builder.setHeader(Exchange.CONTENT_TYPE, contentType);
}
}
use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.
the class BasicHttpTest method postInputStreamWithContentLengthAsBodyGenerator.
@Test
public void postInputStreamWithContentLengthAsBodyGenerator() throws Throwable {
withClient().run(client -> {
withServer(server).run(server -> {
HttpHeaders h = new DefaultHttpHeaders();
h.add(CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
server.enqueue(new AbstractHandler() {
EchoHandler chain = new EchoHandler();
@Override
public void handle(String target, org.eclipse.jetty.server.Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
assertNull(request.getHeader(TRANSFER_ENCODING.toString()));
assertEquals(request.getHeader(CONTENT_LENGTH.toString()), Integer.toString("{}".getBytes(StandardCharsets.ISO_8859_1).length));
chain.handle(target, request, httpServletRequest, httpServletResponse);
}
});
byte[] bodyBytes = "{}".getBytes(StandardCharsets.ISO_8859_1);
InputStream bodyStream = new ByteArrayInputStream(bodyBytes);
client.preparePost(getTargetUrl()).setHeaders(h).setBody(new InputStreamBodyGenerator(bodyStream, bodyBytes.length)).execute(new AsyncCompletionHandlerAdapter() {
@Override
public Response onCompleted(Response response) throws Exception {
assertEquals(response.getStatusCode(), 200);
assertEquals(response.getResponseBody(), "{}");
return response;
}
}).get(TIMEOUT, SECONDS);
});
});
}
use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.
the class SimpleAsyncHttpClientTest method stringBuilderBodyConsumerTest.
@Test(groups = "standalone")
public void stringBuilderBodyConsumerTest() throws Exception {
try (SimpleAsyncHttpClient client = //
new SimpleAsyncHttpClient.Builder().setPooledConnectionIdleTimeout(//
100).setMaxConnections(//
50).setRequestTimeout(//
5 * 60 * 1000).setUrl(//
getTargetUrl()).setHeader("Content-Type", "text/html").build()) {
StringBuilder s = new StringBuilder();
Future<Response> future = client.post(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes())), new AppendableBodyConsumer(s));
Response response = future.get();
assertEquals(response.getStatusCode(), 200);
assertEquals(s.toString(), MY_MESSAGE);
}
}
use of org.asynchttpclient.request.body.generator.InputStreamBodyGenerator in project async-http-client by AsyncHttpClient.
the class SimpleAsyncHttpClientTest method requestByteArrayOutputStreamBodyConsumerTest.
@Test(groups = "standalone")
public void requestByteArrayOutputStreamBodyConsumerTest() throws Exception {
try (SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder().setUrl(getTargetUrl()).build()) {
ByteArrayOutputStream o = new ByteArrayOutputStream(10);
Future<Response> future = client.post(new InputStreamBodyGenerator(new ByteArrayInputStream(MY_MESSAGE.getBytes())), new OutputStreamBodyConsumer(o));
Response response = future.get();
assertEquals(response.getStatusCode(), 200);
assertEquals(o.toString(), MY_MESSAGE);
}
}
Aggregations