3

I need to use Async Http Client (https://github.com/sonatype/async-http-client ) to post an byte array to URL.Content type is octet-stream.

How Do I do it using async http client. Should I use ByteArrayBodyGenerator ? Is there any example code to see how it is done?

If the byte array is already in memory, is it better to use ByteArrayInputStream and use RequestBuilder.setBody(InputStream)

1 Answer 1

2

It is suggested in the docs to not to use InputStream in setBody, because in order to get the content length, the library will need to load everything in memory.

And it seems that ByteArrayBodyGenerator has the same issue. To get the content length it uses a call to bytes.length() and bytes is your byte array (private final byte[] bytes;). So, to get the length of a byte array, the array needs to be loaded in memory.

Here is the source from github: https://github.com/sonatype/async-http-client/blob/master/src/main/java/com/ning/http/client/generators/ByteArrayBodyGenerator.java

You may write your own BodyGenerator implementation to avoid the issue.

Also you asked for an example of using BodyGenerator:

final SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder()
                .setRequestTimeoutInMs(Integer.MAX_VALUE)
                .setUrl(url)
                .build();

client.post(new ByteArrayBodyGenerator(YOUR_BYTE_ARRAY)).get();

And if you want to use legacy API:

final AsyncHttpClientConfig config
     = new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(Integer.MAX_VALUE).build();

final AsyncHttpClient client = new AsyncHttpClient(config);

client.preparePost(url)
        .setBody(new ByteArrayBodyGenerator(YOUR_BYTE_ARRAY))
        .execute()
        .get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.