2012-08-15 58 views
0

我想通過http GET通過休息服務下載apk文件。接收的格式是JSON。我能夠接收數據,但在反序列化爲java對象時失敗。我收到Outofmemory錯誤。Android下載文件 - 傑克遜readvalue無法加載java類 - 堆大小錯誤

我正在Asyn Task中運行文件下載過程。是否有其他更好的選擇來實現相同的功能。該apk約2 MB。從WCF服務中的數據的Base64在JSON

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]); 
    } 



} 

回答

0

編碼,如果JSON庫是一個2MB的JSON文件barfing我也不會感到驚訝。

我知道它可能不是改變API的選項,但是用JSON返回二進制數據很奇怪。這不是爲了這個。 API應該提供兩個端點,一個獲取對象元數據,包括指向內容的鏈接,另一個僅以二進制形式返回內容。

你也可以嘗試另一個JSON庫。

+0

謝謝Jeffrey。我可以直接從網址直接下載文件,但出於安全考慮,我們希望使用服務,因爲我們在標頭中傳入了令牌。正如你所說,我可以從服務中獲取元數據。 – user1408321 2012-08-16 15:44:15