我正在做一个http获取请求。我需要接收大量数据,但在读取数据时出现OutOfMemory异常。从http读取数据时发生OutOfMemory错误获取请求android
我的代码:
public static String getData(String url) throws CustomException {
// http post
InputStream is = null;
StringBuilder sb = null;
String result = null;
HttpGet httppost;
HttpEntity entity;
try {
HttpClient httpclient = new DefaultHttpClient();
httppost = new HttpGet(url);
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
throw new CustomException("Could not establish network connection");
}
// convert response to string
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
byte buffer[] = new byte[1024];
while ((c = is.read(buffer)) > -1)
baos.write(buffer, 0, c); //**OutOfMemory Exception.**
byte[] data = baos.toByteArray();
is.close();
result = new String(data, 0, data.length, "utf-8");
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
throw new CustomException("Error parsing the response");
}
return result;
}
请建议我如何解决这个问题。
+0
有这么多的记录多数民众赞成为什么..我想你应该安装应用程序在SD卡或手机存储.. –
+0
老兄,该网址返回大量的数据。不要将它添加到内存中。使用文件系统。 –