Java下载网络文件入门教程

一、选取下载文件的方式

Java下载网络文件有多种方式:URL类、HttpURLConnection类、Apache HttpClient类等。对于小文件,可以使用URL类,对于大文件和需要进行登录认证等,可以使用HttpURLConnection类或Apache HttpClient类。以下是使用URL类下载文件的示例代码:

<span style="color: #000000;">public static void downloadFileFromUrl(String urlString, String savePath) throws Exception {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    InputStream inputStream = conn.getInputStream();
    FileOutputStream outputStream = new FileOutputStream(savePath);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, len);
    }
    outputStream.close();
    inputStream.close();
}</span>

调用方法:downloadFileFromUrl(“http://example.com/file.zip”, “C:/Downloads/file.zip”)

二、设置请求头和连接超时

在使用HttpURLConnection类下载文件时,可以通过设置请求头和连接超时来自定义请求。以下是设置请求头和连接超时的示例代码:

<span style="color: #000000;">public static void downloadFileFromUrl(String urlString, String savePath) throws Exception {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);

    InputStream inputStream = conn.getInputStream();
    FileOutputStream outputStream = new FileOutputStream(savePath);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, len);
    }
    outputStream.close();
    inputStream.close();
}</span>

调用方法:downloadFileFromUrl(“http://example.com/file.zip”, “C:/Downloads/file.zip”)

三、使用Apache HttpClient类下载文件

Apache HttpClient是一个Java HTTP客户端库,可以实现HTTP请求的发送和接收。以下是使用Apache HttpClient类下载文件的示例代码:

<span style="color: #000000;">public static void downloadFileFromUrl(String urlString, String savePath) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(urlString);
    CloseableHttpResponse response = httpClient.execute(httpGet);

    HttpEntity entity = response.getEntity();
    InputStream inputStream = entity.getContent();
    FileOutputStream outputStream = new FileOutputStream(savePath);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, len);
    }
    outputStream.close();
    inputStream.close();

    response.close();
    httpClient.close();
}</span>

调用方法:downloadFileFromUrl(“http://example.com/file.zip”, “C:/Downloads/file.zip”)

四、使用线程池下载多个文件

如果需要下载多个文件,可以使用线程池来提高下载效率。以下是使用线程池下载多个文件的示例代码:

<span style="color: #000000;">public class DownloadTask implements Runnable {
    private String url;
    private String savePath;

    public DownloadTask(String url, String savePath) {
        this.url = url;
        this.savePath = savePath;
    }

    @Override
    public void run() {
        try {
            downloadFileFromUrl(url, savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public static void downloadFilesFromUrls(List<String> urlList, List<String> savePathList) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < urlList.size(); i++) {
        executor.execute(new DownloadTask(urlList.get(i), savePathList.get(i)));
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(1000);
    }
}</span>

调用方法:

List<String> urlList = Arrays.asList("http://example.com/file1.zip", "http://example.com/file2.zip");
List<String> savePathList = Arrays.asList("C:/Downloads/file1.zip", "C:/Downloads/file2.zip");
downloadFilesFromUrls(urlList, savePathList);

原创文章,作者:WGPAN,如若转载,请注明出处:https://www.506064.com/n/317750.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
WGPANWGPAN
上一篇 2025-01-11 16:27
下一篇 2025-01-11 16:27

相关推荐

发表回复

登录后才能评论