从android发布文件时的内存问题

时间:2011-09-06 11:51:45

标签: android memory http-post

当我尝试从我的Android应用程序上传图像或更大的文件时,它会因OutOfMemoryException而崩溃。我想知道是否有其他方法可以做到这一点。

我在两个不同的地方发生了应用程序崩溃:

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

有什么想法吗?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

这是因为图像尺寸太大,如何解决此问题有一些解释,我将指出一个已经被问过的问题。

Strange out of memory issue while loading an image to a Bitmap object

希望这会有所帮助。