`

HttpURLConnection下载文件

 
阅读更多
public class HttpDownloadUtility
{

    private static final Logger logger = LoggerFactory.getLogger(HttpDownloadUtility.class);

    private static final int BUFFER_SIZE = 4096;
    private static final int END_OF_FILE = -1;

    public static boolean downloadFile(String fileURL, File saveDir)
    {
        return downloadFile(fileURL, saveDir, null);
    }

    public static boolean downloadFile(String fileURL, File saveDir, String fileName)
    {
        HttpURLConnection httpConn = null;
        try
        {
            URL url = new URL(fileURL);
            httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // always check HTTP response code first
            if (responseCode == HttpURLConnection.HTTP_OK)
            {

                String disposition = httpConn.getHeaderField("Content-Disposition");
                String contentType = httpConn.getContentType();
                int contentLength = httpConn.getContentLength();

                if (StringUtils.isEmpty(fileName))
                    fileName = parseFileName(fileURL, disposition);

                logger.info("Content-Type = " + contentType);
                logger.info("Content-Disposition = " + disposition);
                logger.info("Content-Length = " + contentLength);
                logger.info("fileName = " + fileName);

                if (!saveDir.exists())
                {
                    logger.info("Creating File Destination Folder  " + saveDir.getAbsolutePath());
                    saveDir.mkdirs();
                }

                File savedFile = saveFile(saveDir, httpConn, fileName);
                logger.info("File downloaded to " + savedFile.getAbsolutePath());
                return true;
            }
            else
            {
                logger.warn("No file to download. Server replied HTTP code: " + responseCode);
                return false;
            }
        }
        catch (Exception e)
        {
            logger.error("downloading failed from URL " + fileURL, e);
            return false;
        }
        finally
        {
            if (null != httpConn)
                httpConn.disconnect();
        }
    }

    private static String parseFileName(String fileURL, String disposition)
    {
        String fileName = "";
        if (disposition != null)
        {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0)
            {
                fileName = disposition.substring(index + 10, disposition.length() - 1);
            }
        }
        else
        {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
        }
        return fileName;
    }

    private static File saveFile(File saveDir, HttpURLConnection httpConn, String fileName)
        throws IOException, FileNotFoundException
    {
        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();

        File saveFile = new File(saveDir, fileName);

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream(saveFile);

        int bytesRead = END_OF_FILE;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != END_OF_FILE)
        {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();
        return saveFile;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics