我需要使用异步Http客户端(https://github.com/sonatype/async-http-client )来发布一个字节数组到URL.Content类型是八位位流。
如何使用异步http客户端执行此操作。我应该使用ByteArrayBodyGenerator吗?有没有什么示例代码来看看它是如何完成的?
如果字节数组已经在内存中,使用ByteArrayInputStream和RequestBuilder.setBody(InputStream)哪个更好?
发布于 2012-05-15 21:49:25
文档中建议不要在setBody中使用InputStream,因为为了获得内容长度,库需要加载内存中的所有内容。
看起来ByteArrayBodyGenerator也有同样的问题。为了获得内容长度,它调用bytes.length(),bytes是字节数组(私有的最终byte[]字节;)。因此,要获得字节数组的长度,需要将该数组加载到内存中。
这是来自github的源代码:https://github.com/sonatype/async-http-client/blob/master/src/main/java/com/ning/http/client/generators/ByteArrayBodyGenerator.java
您可以编写自己的BodyGenerator实现来避免这个问题。
您还要求提供一个使用BodyGenerator的示例:
final SimpleAsyncHttpClient client = new SimpleAsyncHttpClient.Builder()
.setRequestTimeoutInMs(Integer.MAX_VALUE)
.setUrl(url)
.build();
client.post(new ByteArrayBodyGenerator(YOUR_BYTE_ARRAY)).get();如果你想使用传统的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();https://stackoverflow.com/questions/9780007
复制相似问题