Android -- 工具类(五):[InternetUtil]网络 (文件下载,图片预览)

Android – 工具类(五):[InternetUtil]网络 (文件下载,图片预览)

public class InternetUtil {
    private static final String TAG = "InternetUtil";
    //从有效图片URL连接获取数据流,解析为bitmap便于显示
    public static Bitmap getBitmapFromUrl(String imgUrl){
        Bitmap bitmap = null;
        try {
            URL url = new URL(imgUrl);
            InputStream inputStream = url.openStream();

            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //将图片url先解析成bitmap, 然后保存到本地
    public static void downloadImgFromUrl(String imgUrl, String path, String fileName) {
        Bitmap bitmap = getBitmapFromUrl((imgUrl));
        BitmapUtil.bitmap2Local(bitmap, path, fileName);
    }

    //从有效资源文件url下载资源到本地(类型不限)
    public static void downloadFile(String strUrl, String path, String fileName) {
        File file = new File(path+File.separator+fileName);

        if (file.exists()) {
            //--------------------------
        } else {
            try {
                URL url = new URL(strUrl);

                //===============================================
                HttpURLConnection http = (HttpURLConnection) url.openConnection();;
                http.connect();
                int code = http.getResponseCode();
                if(code!=200){
                    //connect error
                    Log.d(TAG, "connect failed!!!");
                    return;
                }
                //length of file
                int length = http.getContentLength();
                //================================================

                InputStream inputStream = http.getInputStream();

                byte[] buffer = new byte[1024];
                int len;
                OutputStream outputStream = new FileOutputStream(file);
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                Log.d(TAG, "download successful!");
                outputStream.close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值