Read InputStream from HttpURLConnection - Android Network

Android examples for Network:URL

Description

Read InputStream from HttpURLConnection

Demo Code


//package com.java2s;
import android.app.ProgressDialog;
import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static File getApkFile(String url, ProgressDialog pd) {
        //?? ??sd ???????
        int last = url.lastIndexOf("/");
        File file = new File(Environment.getExternalStorageDirectory(),
                url.substring(last + 1));
        try {//w  w w  .j  a v a 2s . c  o  m
            URL u = new URL(url);
            HttpURLConnection con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(5000);
            if (con.getResponseCode() == 200) {
                pd.setMax(con.getContentLength());
                int num = 0;
                InputStream is = con.getInputStream();
                FileOutputStream os = new FileOutputStream(file);
                byte[] buffer = new byte[1024 * 5];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                    num += len;
                    Thread.sleep(30);
                    pd.setProgress(num);
                }
                os.flush();
                os.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
}

Related Tutorials