EntityUtils的toByteArray方法在移动开发中需要注意的问题

本文详细解析了HttpClient4.0中EntityUtils的toByteArray方法在移动开发中的使用注意事项。介绍了如何处理超过Integer.MAX_VALUE大小的数据及内存分配问题,避免程序出现OutOfMemoryError错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

HttpClient4.0中EntityUtils的toByteArray方法在移动开发中需要注意一个问题,Integer.MAX_VALUE的值为2GB,二手机内存极为有限,无法分配那么多的空间,所以可能会OOM

public static byte[] toByteArray(final HttpEntity entity) throws IOException {
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }
        InputStream instream = entity.getContent();
        if (instream == null) {
            return null;
        }
        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
        }
        int i = (int)entity.getContentLength();
        if (i < 0) {
            i = 4096;
        }
        ByteArrayBuffer buffer = new ByteArrayBuffer(i);
        try {
            byte[] tmp = new byte[4096];
            int l;
            while((l = instream.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
        } finally {
            instream.close();
        }
        return buffer.toByteArray();
    }

`bytes = EntityUtils.toByteArray(entity);` 是一个常见的代码行,它的作用是将 HTTP 响应实体转换为字节数组。在发送 HTTP 请求后,服务器会返回一个 HTTP 响应,响应中包含了实体信息,例如文件、图片等。`EntityUtils.toByteArray(entity)` 方法用于将响应中的实体对象转换成字节数组。 一般情况下,我们可以将字节数组写入本地文件,例如: ```java HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); FileOutputStream fos = new FileOutputStream(new File("test.jpg")); fos.write(bytes); fos.close(); ``` 在上面的示例中,我们执行了一个 HTTP GET 请求,并获取了响应的实体对象。然后,我们使用 `EntityUtils.toByteArray(entity)` 方法将实体对象转换成字节数组,并将字节数组写入本地文件 "test.jpg"。 需要注意的是,如果实体较大,将其转换为字节数组可能会导致内存溢出。因此,我们可以使用流的方式处理实体,例如: ```java HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); OutputStream outputStream = new FileOutputStream(new File("test.jpg")); int len; byte[] buffer = new byte[1024]; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); ``` 在上面的示例中,我们通过 `entity.getContent()` 方法获取实体的输入流,并使用 `OutputStream` 将实体内容写入本地文件 "test.jpg"。这种方式可以避免将整个实体加载到内存中,从而减少内存消耗。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值