安卓(Android) 怎么使用httpurlconnection从url下载apk文件

2019年10月17日21:19:22安卓(Android) 怎么使用httpurlconnection从url下载apk文件已关闭评论 1,024 848字阅读2分49秒

1.简介

安卓(Android) 怎么使用httpurlconnection从url下载apk文件?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;
import android.os.Environment;

public class Main {
    public static File getApkFile(String url) {
        int last = url.lastIndexOf("/");
        File file = new File(Environment.getExternalStorageDirectory(),
                url.substring(last + 1));
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();
                FileOutputStream os = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                os.flush();
                os.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
}

 
继续阅读
编程十万个怎么办