我正在尝试通过 http GET 通过休息服务下载 apk 文件。收到的格式是 JSON。我能够接收数据,但在反序列化为 java 对象时失败。我得到内存不足错误。
我正在 Asyn 任务中运行文件下载过程。是否有其他更好的选择来实现相同的功能。该 apk 约为 2 MB。来自 wcf 服务的数据是以 json 格式编码的 Base64
private class DownloadFile extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... sUrl)
{
try
{
URL url = new URL(sUrl[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-Type", "application/json");
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("Device","13");
c.setRequestProperty("Authorization","toughsecurity");
c.setDoInput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "app.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
if(c.getResponseCode()==HttpURLConnection.HTTP_OK)
{
OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/download/"+"temp.txt");
int read = 0;
byte[] bytes = new byte[1024];
while ((read = c.getInputStream().read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
InputStream in=new FileInputStream(Environment.getExternalStorageDirectory() + "/download/"+"temp.txt");
ObjectMapper mapper=new ObjectMapper();
AppDownload download= mapper.readValue(in, AppDownload.class);
byte[] data1=Base64Coder.decodeLines(download.Data);
byte[] content = data1;
int size = content.length;
InputStream is1 = null;
byte[] b = new byte[size];
is1 = new ByteArrayInputStream(content);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is1.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
}
c.disconnect();
}
catch (Exception e)
{
Log.e("Jackson error",e.getMessage());
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// mProgressDialog.setProgress(progress[0]);
}
}