banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

[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. 写了一个简单的上传代码,供参考

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

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.