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

在Android开发中,使用HttpURLConnection上传大文件易出现OOM问题,建议使用Apache HttpComponents的组件HttpClient进行文件上传处理。本文介绍了下载并导入HttpClient组件的方法,给出简单上传代码示例,还提及相关配置及封装方法,同时提供了下载地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做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

PS:HttpURLConnection我研究了半天,无论参数如何调整,都不行,因为我这里无法更改服务端,最后还是选择了HttpClient,简单几行代码,非常省事。

2022年10月25日,目前使用HttpClient,需要这些配置,

①下载httpmime-4.1.1.jar 这个放进lib;② 配置

useLibrary 'org.apache.http.legacy'语句。

示例如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        ...
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        useLibrary 'org.apache.http.legacy'

    }

    
}

dependencies {
    ...
    implementation files('libs/httpmime-4.1.1.jar')


}

另外这里还可以简单封装一下,根据自己的项目进行修改,参考如下:

android http上传,Android HttpClient上传文件(亲测,成功)

Android HttpClient上传文件  的一个封装方法。里面有一小段代码是处理获取JSON格式数据

System.out.println("executing request " + httppost.getRequestLine());  返回协议和返回码

正确的话是 http 1.1 200

System.out.println(EntityUtils.toString(resEntity,"utf-8"));

获取处理后的页面内容

android并不自带MultipartEntity吧?

对的。把httpmime-4.1.1.jar 这个放进lib中就可以使用 MultipartEntity了

下载地址:http://pan.baidu.com/share/link?shareid=90009&uk=4012369003

public class HttpClientUtil {

    public static String post(String pathToOurFile,String urlServer) throws ClientProtocolException, IOException, JSONException {

        HttpClient httpclient = new DefaultHttpClient();

        //设置通信协议版本
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        //File path= Environment.getExternalStorageDirectory(); //取得SD卡的路径

        //String pathToOurFile = path.getPath()+File.separator+"ak.txt"; //uploadfile

        //String urlServer = "http://192.168.1.88/test/upload.php";

        HttpPost httppost = new HttpPost(urlServer);

        File file = new File(pathToOurFile);

        MultipartEntity mpEntity = new MultipartEntity(); //文件传输

        ContentBody cbFile = new FileBody(file);

        mpEntity.addPart("userfile", cbFile); // 对应的

        httppost.setEntity(mpEntity);

        System.out.println("executing request " + httppost.getRequestLine());

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());//通信Ok

        String json="";

        String path="";

        if (resEntity != null) {

        //System.out.println(EntityUtils.toString(resEntity,"utf-8"));

            json= EntityUtils.toString(resEntity,"utf-8");

            JSONObject p=null;

            try{

                p=new JSONObject(json);

                path=(String) p.get("path");

            }catch(Exception e){

                e.printStackTrace();

            }

        }

        if (resEntity != null) {

            resEntity.consumeContent();

        }

        httpclient.getConnectionManager().shutdown();

        return path;

    }
}

原文地址:https://blog.youkuaiyun.com/weixin_42533910/article/details/117592410

[Android]解决HttpURLConnection上传大文件时出现OOM问题 | 李大仁博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值