使用httpclient进行文件下载
生活随笔
收集整理的這篇文章主要介紹了
使用httpclient进行文件下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用httpclient進行文件下載獲取文件名獲取方式
? ? 先從返回頭的content-Disposition中獲取,如果沒有再從下載的Url中獲取。
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils;import java.io.*; import java.net.*; import java.util.regex.Matcher; import java.util.regex.Pattern;@Slf4j public class FilesUtils {private final static Pattern pattern = Pattern.compile(".*fileName=(.*)");/*** 文件下載** @param httpUrl 下載的url* @return*/public static FileMetaInfoDTO downLoadFromUrl(String httpUrl) throws IOException {File file = null;FileMetaInfoDTO fileMetaInfoDTO = null;try {// 統一資源URL url = new URL(httpUrl);// 連接類的父類,抽象類URLConnection urlConnection = url.openConnection();// http的連接類HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;// 設定請求的方法,默認是GEThttpURLConnection.setRequestMethod("GET");// 設置字符編碼httpURLConnection.setRequestProperty("Charset", "UTF-8");urlConnection.setConnectTimeout(MccConfigUtil.getDonwLoadTimeOut());// 打開到此 URL 引用的資源的通信鏈接(如果尚未建立這樣的連接)。httpURLConnection.connect();String suffix = getSuffix(httpUrl);if (StringUtils.isEmpty(suffix)) {suffix = ".tmp";}file = File.createTempFile("httpdonwFile", suffix);BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}FileOutputStream out = new FileOutputStream(file);int size = 0;int len = 0;byte[] buf = new byte[1024];while ((size = bin.read(buf)) != -1) {len += size;out.write(buf, 0, size);}bin.close();out.close();String fileName = tryGetFileName(urlConnection);fileMetaInfoDTO = new FileMetaInfoDTO(fileName, file);} catch (MalformedURLException e) {log.error("downLoad file eror url = {} ", httpUrl, e);} catch (IOException e) {log.error("downLoad file eror url = {} ", httpUrl, e);} finally {return fileMetaInfoDTO;}}private static String tryGetFileName(URLConnection conn) {String contentDisposition = null;try {String disposition = conn.getHeaderField("content-Disposition");if (!StringUtils.isEmpty(disposition)) {contentDisposition = URLDecoder.decode(disposition, "UTF-8");Matcher matcher = pattern.matcher(contentDisposition);return matcher.group(1);} else {String path = conn.getURL().getPath();Integer start = path.lastIndexOf('/') + 1;String fileName = path.substring(start);return URLDecoder.decode(fileName, "UTF-8");}} catch (UnsupportedEncodingException e) {log.error("文件名解析失敗 url = {}", conn.getURL(), e);} catch (Exception e) {log.error("文件名解析失敗 url = {}", conn.getURL(), e);}return null;}/*** 從輸入流中獲取字節數組** @param inputStream* @return* @throws IOException*/public static byte[] readInputStream(InputStream inputStream) throws IOException {byte[] buffer = new byte[1024];int len = 0;ByteArrayOutputStream bos = new ByteArrayOutputStream();while ((len = inputStream.read(buffer)) != -1) {bos.write(buffer, 0, len);}bos.close();return bos.toByteArray();}public static String getSuffix(String path) {String suffix = StringUtils.substringAfterLast(path, ".");suffix = StringUtils.substringBeforeLast(suffix, "?");suffix = StringUtils.substringBeforeLast(suffix, "@");return "." + suffix;}@Data public static class FileMetaInfoDTO {String fileName;File file;public FileMetaInfoDTO(String fileName, File file) {this.fileName = fileName;this.file = file;}public FileMetaInfoDTO() {} } }?
總結
以上是生活随笔為你收集整理的使用httpclient进行文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python Django项目实例二
- 下一篇: PS 抠图技巧