HttpClient 下载图片/视频并更新相册

2019-05-24  本文已影响0人  一个冬季
下载工具封装类
/**
* @date: 2019/5/23 0023
* @author: gaoxiaoxiong
* @description:图片,视频下载工具
**/
public class DownFileUtils {
    private String TAG = DownFileUtils.class.getSimpleName();
    private static DownFileUtils downFileUtils;
    public static DownFileUtils getInstance(){
        if (downFileUtils == null){
            downFileUtils = new DownFileUtils();
        }
        return downFileUtils;
    }

    /**
    * @date: 2019/5/23 0023
    * @author: gaoxiaoxiong
    * @description: 下载图片
    **/
    public File getPicFromServer(String path, Handler handler) throws Exception {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {          //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            long time = System.currentTimeMillis();
            File file = null;
            file = new File(FileUtils.getInstance().getDIRECTORY_PICTURESDir(), time + ".jpg");
            Log.i(TAG, file.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            long total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                Message message = handler.obtainMessage();
                message.what = 0;
                handler.sendMessage(message);
            }
            Message message = handler.obtainMessage();
            message.what = 1;
            message.obj = file.getAbsolutePath();
            handler.sendMessage(message);
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
    * @date: 2019/5/23 0023
    * @author: gaoxiaoxiong
    * @description:下载视频,obj参数,返回带进度数字,下载成功后obj参数返回带视频成功地址的路径
    **/
    public File getVideoFromServer(String path, Handler handler) throws Exception {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {          //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            long time = System.currentTimeMillis();
            File file = null;
            String prefix = path.substring(path.lastIndexOf(".")+1);
            file = new File(FileUtils.getInstance().getDIRECTORY_MOVIESDir(),time+"."+prefix);
            Log.i(TAG, file.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            long total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                Message message = handler.obtainMessage();
                message.what = 0;
                //返回已经下载的量
                float f = new BigDecimal(total / (double) conn.getContentLength()).floatValue();
                f = f * 100;
                message.obj = f;
                handler.sendMessage(message);
            }
            Message message = handler.obtainMessage();
            message.what = 1;
            message.obj = file.getAbsolutePath();
            handler.sendMessage(message);
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

 /**
    * @date: 2019/6/21 0021
    * @author: gaoxiaoxiong
    * @description:下载文件
    **/
    public File getFileFromServer(String path, Handler handler) throws Exception {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {          //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            //long time = System.currentTimeMillis();
            String fileName = conn.getHeaderField("Content-Disposition");
            if (fileName == null || fileName.length() < 1) {
                // 通过截取URL来获取文件名
                URL downloadUrl = conn.getURL(); // 获得实际下载文件的URL
                fileName = downloadUrl.getFile();
                fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            } else {
                fileName = URLDecoder.decode(fileName.substring(
                        fileName.indexOf("filename=") + 9), "UTF-8");
                // 有些文件名会被包含在""里面,所以要去掉,不然无法读取文件后缀
                fileName = fileName.replaceAll("\"", "");
            }
            File file = null;
            file = new File(FileUtils.getInstance().getDiskMusicCacheDir(),fileName);
            Log.i(TAG, file.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            long total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                Message message = handler.obtainMessage();
                message.what = 0;
                //返回已经下载的量
                float f = new BigDecimal(total / (double) conn.getContentLength()).floatValue();
                f = f * 100;
                message.obj = f;
                handler.sendMessage(message);
            }
            Message message = handler.obtainMessage();
            message.what = 1;
            message.obj = file.getAbsolutePath();
            handler.sendMessage(message);
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

}
更新相册

msg.obj表示我下载完后,图片的路径地址

  MediaScannerConnection.scanFile(fragment.getActivity(), new String[]{(String) msg.obj}, new String[]{"image/jpeg"}, new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String s, Uri uri) {

                            }
                        });
更新视频

msg.obj表示我下载完成后,视频的路径地址

  MediaScannerConnection.scanFile(fragment.getActivity(), new String[]{(String) msg.obj}, null, new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String s, Uri uri) {

                        }
                    });
上一篇下一篇

猜你喜欢

热点阅读