How to POST binary bytes using java async http client (ning) library

I need to use Async Http Client ( to send byte array to url. The content type is an octet stream.

How to do it using async http client. Should I be using ByteArrayBodyGenerator? Is there any sample code to see how this is done?

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


source to share

1 answer

In documents, it is recommended not to use InputStream in setBody

, because in order to get the length of the content, the library will need to load everything in memory.

And it looks like ByteArrayBodyGenerator has the same problem. To get the length of the content, it uses the call bytes.length()

and bytes

- your byte array (private final byte [] bytes;). Thus, to get the length of a byte array, the array must be loaded into memory.

Here is the source from github:

You can write your own BodyGenerator implementation to avoid the problem.

Also you asked for an example using the BodyGenerator:

final SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder()
                .build(); ByteArrayBodyGenerator(YOUR_BYTE_ARRAY)).get();


And if you want to use the deprecated API:

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

final AsyncHttpClient client = new AsyncHttpClient(config);

        .setBody(new ByteArrayBodyGenerator(YOUR_BYTE_ARRAY))




All Articles