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/zh-hk/n/317750.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
WGPAN的頭像WGPAN
上一篇 2025-01-11 16:27
下一篇 2025-01-11 16:27

相關推薦

發表回復

登錄後才能評論