从Web服务读取响应时出现内存不足错误

时间:2012-03-10 07:09:25

标签: android web-services out-of-memory

我试图调用一个Web服务,响应包含一个大字符串,内存不足问题代码是

 URL u = new URL(SharedVariables.server);
           URLConnection uc = u.openConnection();
           HttpURLConnection connection = (HttpURLConnection) uc;
           connection.setConnectTimeout(SharedVariables.connectionTimedOutValue);
           connection.setDoOutput(true);
           connection.setDoInput(true);
           connection.setRequestProperty("SOAPAction", SOAP_ACTION);
           connection.setRequestMethod("POST");
           connection.setRequestProperty("Content-type", "text/xml; charset=utf-8");

           String xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
                            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> "+ 
                            "<soap:Body>"+
                            "<GetCaseCriminalTicketLinks xmlns=\"http://tempuri.org/\">"+   
                            Req.getRequestXml()+                            
                            "</GetCaseCriminalTicketLinks>"+
                            "</soap:Body>"+
                            "</soap:Envelope>";        

           OutputStream out = connection.getOutputStream();
                Writer wout = new OutputStreamWriter(out);
                wout.write(xmldata);
                wout.flush();                   
                out.flush();                    


              BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()),8 * 1024);

              String result;    

              while ((result=rd.readLine()) != null) {


              int length = result.length();               
               String temp = result.substring(316, (length - 100));           

               JSONObject tempJson = new JSONObject(temp);}

日志

Caused by: java.lang.OutOfMemoryError
at java.lang.String.<init>(String.java:513)
at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:650)
at java.lang.StringBuilder.toString(StringBuilder.java:664)
at java.io.BufferedReader.readLine(BufferedReader.java:398)

此行正在导致

while ((result=rd.readLine()) != null) 

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:0)

对于while ((result=rd.readLine()) != null)循环中可用的所有变量,将在堆上创建内存,正如您所提到的那样,您尝试流式传输1 MB数据,循环将耗费很长时间,因此堆已成为堆重载以存储数据。

我的建议:

  1. 尝试传输最少量的数据并检查
  2. 避免在循环内实例化对象,而是使用引用。
  3. 找到增加JVM内存大小的方法
  4. 要考虑的链接是:

    Increase heap size in java

    JVM-Java increase heap size