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(); 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; }); } 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 = 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); } } } } }
科普知事网