Home > 语言编程 > [Android]解决HttpURLConnection上传大文件时出现OOM问题

[Android]解决HttpURLConnection上传大文件时出现OOM问题

Android开发时通常使用HttpURLConnection来进行文件的上传,但是,如果需要上传较大文件时就不建议使用了,HttpURLConnection使用时如果编写程序不当会在上传时导致另人抓狂的OOM问题,在Android开发时如果需要上传较大文件建议使用Apache HttpComponents的组件HttpClient来进行文件上传处理。同时这个组件目前还有Android专用的版本(HttpClient for Android),具体用法如下:
1.下载并导入HttpClient组件,可以只下载httpmime-4.1.1.jar或直接下载Android HttpClient版的源代码

2.写了一个简单的上传代码,供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
String filePath =  "";       //File Path to set
String fileParam = "";      //Request parameter for file
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");
try {
     MultipartEntity entity = new MultipartEntity();
     File file = new File(filePath);
     ContentBody fileBody = new FileBody(file); // file
     entity.addPart(fileParam, fileBody);
     httpPost.setEntity(entity);
     HttpResponse response = client.execute(httpPost);
     if (response.getStatusLine().getStatusCode() == 200) { // 成功
         //HttpEntity responseEntity = response.getEntity();
         Log.i("TAG", "SUCCESSED");
     } else {
        Log.i("TAG", "FAILED");
     }
 } catch (Exception e) {
     Log.e("TAG", "EXCEPTION");
}

最后附上Apache HttpComponents的下载地址
http://hc.apache.org/downloads.cgi

Categories: 语言编程 Tags:
  1. No comments yet.
  1. No trackbacks yet.