Android 从http Get请求读取数据时发生OutOfMemory错误
我正在执行http Get请求。我需要接收大量数据,但在读取数据时会出现内存异常 我的代码:Android 从http Get请求读取数据时发生OutOfMemory错误,android,out-of-memory,http-get,httpservice,Android,Out Of Memory,Http Get,Httpservice,我正在执行http Get请求。我需要接收大量数据,但在读取数据时会出现内存异常 我的代码: public static String getData(String url) throws CustomException { // http post InputStream is = null; StringBuilder sb = null; String result = null; HttpGet httppost; HttpEntity e
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;
}
我传递给getData的URL是:
请建议我如何解决此问题。收到的文件很大,您需要将响应写入文件而不是ByteArrayOutputStream,然后尝试解析文件的结果
如果可能的话,服务器应该将大文件分成小块。一个可能的解决方案是在从服务器获取结果时实现分页。
之后,您可以逐步将数据写入某个位置。记录太多,这就是原因。。我认为你应该在SD卡或手机存储器中安装这个应用程序。伙计,这个url会返回很多数据。不要把它添加到内存中。使用文件系统。