【问题标题】:Memory problems when posting files from android从android发布文件时的内存问题
【发布时间】:2011-09-06 11:51:44
【问题描述】:

当我尝试从我的 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);

有什么想法吗?

【问题讨论】:

    标签: android memory http-post


    【解决方案1】:

    如果你这样做,整个 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;
    }
    

    【讨论】:

    • Thx 会调查这些库。
    【解决方案2】:

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

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2013-10-02
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多