0
点赞
收藏
分享

微信扫一扫

网络资源下载工具类:java

跟着Damon写代码 2022-04-04 阅读 141
java

网络资源下载工具类

import feign.Feign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 网络资源下载工具类
 */
public class URIDownloadUtil {

    private final static Logger log = LoggerFactory.getLogger(URIDownloadUtil.class);

    private static ExecutorService executorService = Executors.newCachedThreadPool();

    /**
     * 下载资源(异步)
     *
     * @param url
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    public final static Future<byte[]> asyncDownloadURIToBytes(String url) throws MalformedURLException, IOException {
        return executorService.submit(() -> {
            byte[] result = null;

            try {
                result = downloadURIToBytes(url);
            } catch (Exception e) {
                log.error("异步下载资源异常", e);
            }
            return result;
        });
    }

    /**
     * 下载资源
     * @return 资源的二进制数据
     */
    public final static byte[] downloadURIToBytes(String url) throws MalformedURLException, IOException {
        HttpURLConnection httpURLConnection;
        InputStream inputStream = null;
        ByteArrayOutputStream arrayOutputStream = null;
        try {
            URL url_ = new URL(url);

            httpURLConnection = (HttpURLConnection) url_.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(false);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setUseCaches(true);
            httpURLConnection.connect();
            int code = httpURLConnection.getResponseCode();
            log.debug("httpURLConnection ResponseCode = {}", code);
            if (code == 200) {
                // 将得到的数据转化成InputStream
                inputStream = httpURLConnection.getInputStream();

                //读取输入流中的数据
                arrayOutputStream = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];
                int len;
                while ((len = inputStream.read(buff)) != -1) {
                    arrayOutputStream.write(buff, 0, len);
                }

                inputStream.close();

                arrayOutputStream.close();

                return arrayOutputStream.toByteArray();
            } else {
                return null;
            }
        } catch (MalformedURLException e) {
            log.error("URL错误", e);
            throw e;
        } catch (IOException e) {
            log.error("I/O流异常", e);
            throw e;
        } finally {
            if (arrayOutputStream != null) {
                try {
                    arrayOutputStream.close();
                } catch (IOException e) {
                    log.error("关闭arrayOutputStream出现异常", e);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("关闭inputStream出现异常", e);
                }
            }
        }
    }
  }
举报

相关推荐

0 条评论