2011-09-06 34 views
3

當我嘗試從Android應用程序上傳圖片或更大的文件時,它會因OutOfMemoryException而崩潰。我想知道是否有任何替代方法做到這一點。從Android發佈文件時發生內存問題

Ive有兩個不同點的應用程序崩潰:

Base64.encodeToString(bytes, Base64.DEFAULT); 

而且在這些地方的base64字符串是在nameValuPairs集合中的一個值。

HttpClient client = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(uo.WebServiceURL); 
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs); // On this line 
httppost.setEntity(entity); 
HttpResponse response = client.execute(httppost); 

任何想法?

回答

6

如果你這樣做,整個POST必須緩衝在內存中。 這是因爲它需要首先發送Content-Length標頭。

相反,我認爲你想使用Apache HTTP庫,包括 http://developer.android.com/reference/org/apache/http/entity/FileEntity.html 。這將讓它在讀取文件之前計算出長度。你可以用這個答案作爲出發點。但是第二個參數 FileEntity構造函數應該是一個MIME類型(如image/png, text/html等)。

Posting a large file in Android

入住這也.........

由於Schnapple說,你的問題似乎非常廣泛,是混亂的閱讀和理解。

下面是一些通用代碼,用於發送HTTP POST並從服務器獲取響應,儘管這可能會有所幫助。

public String postPage(String url, File data, boolean returnAddr) { 

    ret = null; 

    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); 

    httpPost = new HttpPost(url); 
    response = null; 

    FileEntity tmp = null;  

    tmp = new FileEntity(data,"UTF-8"); 

    httpPost.setEntity(tmp); 

    try { 
     response = httpClient.execute(httpPost,localContext); 
    } catch (ClientProtocolException e) { 
     System.out.println("HTTPHelp : ClientProtocolException : "+e); 
    } catch (IOException e) { 
     System.out.println("HTTPHelp : IOException : "+e); 
    } 
      ret = response.getStatusLine().toString(); 

      return ret; 
} 
+0

Thx將調查這些庫。 – twDuke