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

I need to use Async Http Client (https://github.com/sonatype/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)

+3


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: https://github.com/sonatype/async-http-client/blob/master/src/main/java/com/ning/http/client/generators/ByteArrayBodyGenerator.java

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()
                .setRequestTimeoutInMs(Integer.MAX_VALUE)
                .setUrl(url)
                .build();

client.post(new 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);

client.preparePost(url)
        .setBody(new ByteArrayBodyGenerator(YOUR_BYTE_ARRAY))
        .execute()
        .get();

      

+2


source







All Articles