Download Apk File from URL using HttpURLConnection - Android App

Android examples for App:APK Download

Description

Download Apk File from URL using HttpURLConnection

Demo Code


//package com.java2s;
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 {/*www.j a  v a 2  s. c o  m*/
            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;
    }
}

Related Tutorials