有两种策略可以帮助您解决此问题:
下载时将SOAP XML流直接保存到磁盘。不要将其存储在内存中。 使用SAX样式的解析器对其进行解析,在该解析器中,您无需将整个DOM加载到内存中,而是以块的形式进行解析。 根据要处理的XML的类型,使用SAX解析器通常在代码上更难。您将不得不自己跟踪许多事情,并且将无法在DOM树的各个部分之间“跳转”。但是内存消耗将更低。
但是请注意,许多“高级”网络通信库通常将整个XML DOM加载到内存中,在这里可能就是这种情况。您可能必须自己创建和管理HTTP连接,然后手动解析结果。
只是更新,我发现AndroidHttpTransport中的“ call”方法在此行的内存不足-
if (debug) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true) {
int rd = is.read(buf, 0, 256);
if (rd == -1)
break;
bos.write(buf, 0, rd);
}
bos.flush();
buf = bos.toByteArray(); //Goes out of memory here
responseDump = new String(buf);
is.close();
is = new ByteArrayInputStream(buf);
调用toByteArray会占用大量内存,因此要解决此问题,而不是将响应转换为字节数组,我现在将其直接写入XML文件,并将其保存在我选择的位置。这里 -
if (debug) {
FileOutputStream bos = new FileOutputStream("/data/data/com.mypackage.myapp/response.xml");
byte[] buf = new byte[1048576];
int current = 0; int i=0; int newCurrent = 0;
while ((current = inputStream.read(buf)) != -1) {
newCurrent = newCurrent + current;
Log.d("current", "Current = " + current + " total = "+newCurrent+" i = "+i++);
bos.write(buf, 0, current);
}
bos.flush();
}