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

twD*_*uke 3 memory android http-post

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

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

Base64.encodeToString(bytes, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)

这里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);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Sam*_*iya 6

如果你这样做,整个POST必须缓冲在内存中.这是因为它需要首先发送Content-Length标头.

相反,我认为你想使用Apache HTTP库,包括 http://developer.android.com/reference/org/apache/http/entity/FileEntity.html .这将让它在读取文件之前计算出长度.您可以将此答案作为起点.但是FileEntity构造函数的第二个参数应该是mime类型(如image/png,text/html等).

在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;
}
Run Code Online (Sandbox Code Playgroud)