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();
}